没有地图的图书馆

我正在尝试使用谷歌地点图书馆附近的搜索请求: Https://developers.google.com/maps/documentation/javascript/places#place_search_requests

我只是想把 json 响应放到 html 列表中,现在我想在地图或其他地方显示结果。我根本不想用地图。但是在文件中,它声明必须有一张地图

service = new google.maps.places.PlacesService(**map**);

以便在 PlacesService 函数中将其作为参数传递。我现在要做的是添加一个高度为0的地图,但它仍然消耗大量的内存(我开发了一个 Sencha touch 2应用程序,内存很重要)。有没有办法在没有地图的情况下使用附近的搜索请求?我不想使用 GooglePlaces API,因为它不支持 JSONP 请求。

52270 次浏览

As documented the PlacesService accepts as argument either a map or an node where to render the attributions for the results.

So you only have to use the node (a node being an html element) instead of the map.

Please note: hiding the attributions violates the places-policies(also hiding the map when used as argument, because the map will show the attributions)

This also may be interesting to you: Google places API does this violate the TOC?


Example: in a nutshell

If you're using jQuery:

var service = new google.maps.places.PlacesService($('#tag-id').get(0));

If plain Javascript:

var service = new google.maps.places.PlacesService(document.createElement('div'));

Then carry on as usual with the rest of the example code:

  service.nearbySearch(request, callback);

Example: using details returned

Live demo of this example on jsFiddle.

Note: This example uses jQuery.

<ul class="reviews__content" id="reviews__content">
</ul>
<div id="service-helper"></div>


<script async defer
src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY_HERE&libraries=places&callback=getRelevantGoogleReviews">
</script>
<script type="text/javascript">
window.getRelevantGoogleReviews = function(){
var service = new google.maps.places.PlacesService($('#service-helper').get(0)); // note that it removes the content inside div with tag '#service-helper'


service.getDetails({
placeId: 'ChIJAwEf5VFQqEcRollj8j_kqnE'  // get a placeId using https://developers.google.com/places/web-service/place-id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var resultcontent = '';
for (i=0; i<place.reviews.length; ++i) {
//window.alert('Name:' + place.name + '. ID: ' + place.place_id + '. address: ' + place.formatted_address);
resultcontent += '<li class="reviews__item">'
resultcontent += '<div class="reviews__review-er">' + place.reviews[i].author_name + '</div>';
var reviewDate = new Date(place.reviews[i].time * 1000);
var reviewDateMM = reviewDate.getMonth() + 1;
var reviewDateFormatted = reviewDate.getDate() + '/' + reviewDateMM + '/' + reviewDate.getFullYear();
resultcontent += '<div class="reviews__review-date">' + reviewDateFormatted + '</div>';
resultcontent += '<div class="reviews__review-rating reviews__review-rating--' + place.reviews[i].rating +'"></div>';
if (!!place.reviews[i].text){
resultcontent += '<div class="reviews__review-comment">' + place.reviews[i].text + '</div>';
}
resultcontent += '</li>'
}
$('#reviews__content').append(resultcontent);
}
});
}
</script>

Just seen Man asking in a comment above How to initialise the places service without initialising a map? so I thought I would add it here.

placesService = new google.maps.places.PlacesService($('#predicted-places').get(0));

You will need to create an html element with that id first though.

If you want to get location data from a place_id you can do it using the Geocoder class:Here the documentation. With this class you can pass a place_id to the method geocode() and get coordinates and other location data.

I have come across the same problem.

Why use Maps javascript Api when Places Api is already enabled.Is it an additional price to pay for this simple task?

Maps Javascript API is not used in this code.All the google.maps.Map API methods are taken out. It works fine on jsfiddle.

Just checkout whether it works on local PC.Most of the time it gives the 403 error when i tried running it on local PC storage and using limited requests provided by google API console.

acquire an API key from the google developer console and insert it in the YOUR_API_KEY slot at the script tag of the code Don't try to run the code here.obviously.The API key needs to be replaced.

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">


function initMap() {


var input = document.getElementById('pac-input');


var options = {
types: ['establishment']
};


var autocomplete = new google.maps.places.Autocomplete(input, options);


autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address', 'formatted_phone_number', 'opening_hours', 'website', 'photos']);


autocomplete.addListener('place_changed', placechange);


function placechange() {


var place = autocomplete.getPlace();
var photos = place.photos;


document.getElementById('place_name').textContent = place.name;
document.getElementById('place_id').textContent = place.place_id;
document.getElementById('place_address').textContent = place.formatted_address;
document.getElementById('phone_no').textContent = place.formatted_phone_number;
document.getElementById('open_time').textContent = place.opening_hours.weekday_text[0];
document.getElementById('open_now').textContent = place.opening_hours.open_now;
document.getElementById('photo').src = photos[0].getUrl();
document.getElementById('photo').style = "width:50%;";
document.getElementById('website').textContent = place.website;




}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */


#map {
height: 100%;
}




/* Optional: Makes the sample page fill the window. */


html,
body {
height: 100%;
margin: 0;
padding: 0;
}


.controls {
background-color: #fff;
border-radius: 2px;
border: 1px solid transparent;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
box-sizing: border-box;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
height: 29px;
margin-left: 5px;
margin-top: 10px;
margin-bottom: 10px;
outline: none;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}


.controls:focus {
border-color: #4d90fe;
}


.title {
font-weight: bold;
}


#infowindow-content {
display: none;
}


#map #infowindow-content {
display: inline;
}
<div>
<input id="pac-input" class="controls" type="text" placeholder="Enter a business">
</div>


<div id="info-table">
Name: <span id="place_name"></span><br> Place id: <span id="place_id"></span><br> Address :<span id="place_address"></span><br> Phone : <span id="phone_no"></span><br> Openhours: <span id="open_time"></span><br> Open Now : <span id="open_now"></span><br>  website : <span id="website"></span><br> photo :<br> <img id="photo" src="" style="display:none;" />
</div>


<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br>
<strong>Place ID:</strong> <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>

Was making a custom address autocomplete for a sign up form.

import {useState, useRef, useEffect } from 'React'


function AutoCompleteInput(){


const [predictions, setPredictions] = useState([]);
const [input, setInput] = useState('');
const [selectedPlaceDetail, addSelectedPlaceDetail] = useState({})
const predictionsRef = useRef();




useEffect(
()=>{
try {
autocompleteService.current.getPlacePredictions({ input }, predictions => {
setPredictions(predictions);
});
} catch (err) {
// do something
}
}
}, [input])


const handleAutoCompletePlaceSelected = placeId=>{
if (window.google) {
const PlacesService = new window.google.maps.places.PlacesService(predictionsRef.current);
try {
PlacesService.getDetails(
{
placeId,
fields: ['address_components'],
},
place => addSelectedPlaceDetail(place)
);
} catch (e) {
console.error(e);
}
}
}


return (
<>
<input onChange={(e)=>setInput(e.currentTarget.value)}
<div ref={predictionsRef}
{ predictions.map(prediction => <div onClick={ ()=>handleAutoCompletePlaceSelected(suggestion.place_id)}> prediction.description </div> )
}
</div>
<>
)
}

So basically, you setup the autocomplete call, and get back the predictions results in your local state.

from there, map and show the results with a click handler that will do the follow up request to the places services with access to the getDetails method for the full address object or whatever fields you want.

you then save that response to your local state and off you go.