I am unable to display all the results requested from the Google Places Api..
var Latlng = new google.maps.LatLng(Latitute, Longitute);
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: Latlng,
zoom: 10});
var request = {location: Latlng,types: [type]};
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results,status,pagination) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
if (pagination.hasNextPage) {
pagination.nextPage(); }}}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({map: map,zIndex: 100,position: place.geometry.location});
var request = {reference : place.reference,};
service = new google.maps.places.PlacesService(map);
service.getDetails(request, function detailsDisplay(details, status){
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(status);
$('#placesdata').append('<tr><td><a href='+details.url+'>' + details.name+ '</a></td></tr>');
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
createMarker(place);
}, 200);}});} };
i used pagination and getting 60 results but only can display 20..and 40 using settimeout() function...getting the following error: Uncaught TypeError: Cannot read property 'length' of null. Any clue?
Most likely you are getting OVER_QUERY_LIMIT on line:
if (status == google.maps.places.PlacesServiceStatus.OK)
because you are already creating Markers, which eats up your quota.
Try queuing the details requests for after you have all the list completed, and adding the same timeout logic to check for google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT on this line.
For example you could say:
if (pagination.hasNextPage) {
//add all places to the list
setTimeout('pagination.nextPage()',2000);
} else {
createMarkers(placesList);
}
btw. the Places equivalent of google.maps.GeocoderStatus.OVER_QUERY_LIMIT is google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT and you should use this when using Places.
HTH
I have done all those effort. Thanks for you guys for posting but i got solution. really a good solution. See working example below.
When you call this method to check if it has pages or not
if(pagination.hasNextPage){
pagination.nextPage(); // let this do recursive loop against request.
}
// when nextPage() request finishes
if(pagination.b == null){
// here pagination.b has next page token. so it return null when last request sent.
createMarkers(placesList);
}
Related
I am using the google.maps.places.Autocomplete API and this morning I was getting a 502 Bad Gateway error. It lasted about 10 minutes and started working again. I assume this had to do with the service being unavailable.
I was wondering how I can error handle when this happens. My (javascript) autocomplete code looks like this:
$('#StartAddress').change(function () {
google.maps.event.trigger(startAutocomplete, 'place_changed');
return false;
});
var source, destination;
var directionsDisplay;
var directionsService;
if (typeof google === 'object' && typeof google.maps === 'object') {
directionsService = new google.maps.DirectionsService();
// set up places autocomplete
var start = document.getElementById('StartAddress');
var startAutocomplete = new google.maps.places.Autocomplete(start);
var end = document.getElementById('EndAddress');
var endAutocomplete = new google.maps.places.Autocomplete(end);
// add the places auto complete listener for when the values change
startAutocomplete.addListener('place_changed', function () {
var startAddress = $('#StartAddress').val();
var endAddress = $('#EndAddress').val();
if (endAddress && startAddress) {
GetRoute(startAddress, endAddress, false);
}
});
endAutocomplete.addListener('place_changed', function () {
var endAddress = $('#EndAddress').val();
var startAddress = $('#StartAddress').val();
if (endAddress && startAddress) {
GetRoute(startAddress, endAddress, false);
}
});
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': false });
}
The GetRoute(startAddress, endAddress, false) function is a call to the google.maps.Map and that works fine. It was only the autocomplete service that was down.
Also, is it possible this error occurred because I am using the developer key instead of production? Like the googles dev environment is much more resource limited?
The service was down this time. Try again now.
I have some troubles with the Geocoder from Google Maps.
The main idea is, that I have a list with estates (flat, house, ...) in it and I want to search for Points of Interest (POIs; university, cafe, etc.) nearby the estates with some given range. There is no problem, it works fine.
BUT what I want to do now is, to "delete", or better said, make the markers invisible, which have no Points of Interest in the given range nearby.
In the code below you will see, that I have the geocode in a for loop, and for every estate which it gets it sets the POIs. Now I want to give over the estates which it uses at this time, checks if there are results nearby, if not it should set the marker of the estate on map to null. The problem is, that I can't give over the id of the estate, so I can set the marker to null with this specific ID.
Right now it works partially, but it always deletes the markers randomly. (Currently it is done with some counter to delete the index... but I want to delete it with the id).
So, the main question is, how can I hand over the current ID of the estate from the for loop into the callback and delete the marker with the same ID?
To understand the code i should say that "immo" or "immobilien" is the german word for estates.
Here's the code:
function geocodePoi(geocoder, resultsMap) {
var poiCat = document.getElementById("poi").value;
poiList.push(poiCat);
var address = document.getElementById('address').value;
var poi = document.getElementById('poi').value;
var radius = document.getElementById('range').value;
var poiArray = [];
poiArray.push(poi);
var latlng;
geocoder.geocode({'address': address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.setCenter(results[0].geometry.location);
latlng = results[0].geometry.location;
latlngDic = {lat: latlng.lat(), lng: latlng.lng()};
infowindow = new google.maps.InfoWindow();
for (i = 0; i < immobilien.length; i++) {
currentImmo = immobilien[i].id;
currentImmoList.push(currentImmo);
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: new google.maps.LatLng(immobilien[i].longitude,
immobilien[i].latitude),
radius: radius,
types: poiArray
}, callback);
}
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function callback(results, status) {
if (status === "ZERO_RESULTS") {
setMapOnAllImmo(null, count);
count = count + 1;
}
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
count += 1;
}
}
My project searches the eBay API (using PHP and returns simpleXML) and returns the postcodes of multiple items (5 at the moment). Then uses this information to plot markers on a Google map on my website. What I am trying to do is create multiple info windows along with these markers so I can also return information from the eBay auction and put it in the info window (link to auction, picture of item etc.) but I am having no luck! I cannot seem to get the closures right in my loop and I keep getting the last postcode in the array displayed in the info window rather than the postcode actually associated with that marker (just doing this for test purposes).
What am I doing wrong? Any information will be helpful.
This is my code at the moment:
for (var i = 0; i < msg.length; i++) {
info = msg[i];
console.log(info);
geocoder.geocode( { 'address': msg[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
icon: image,
position: results[0].geometry.location
})
listenMarker(marker);
markerBounds.extend(results[0].geometry.location);
map.fitBounds(markerBounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function listenMarker (marker){
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
You are need to use a function closure on the geocoder call as well (not tested), looks like you might have a problem with your listMarker function also (seems to be missing the definition of "info", if you are depending on the global value of that, that could be your problem):
function geocodeAddress(msg)
{
geocoder.geocode( { 'address': msg}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
icon: image,
position: results[0].geometry.location
})
listenMarker(marker, msg);
markerBounds.extend(results[0].geometry.location);
map.fitBounds(markerBounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
for (var i = 0; i < msg.length; i++) {
info = msg[i];
console.log(info);
geocodeAddress(msg[i]);
}
function listenMarker (marker, info){
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
I've got a Google Maps widget working on an .xhtml page served by a JSF2 project in Java. The map displays, and I have a function for adding markers that works just fine. However, any attempt to use Geocoder seems to result in the returned status of 'ERROR'. Google Maps API mentions no such error status amongst its five possible candidates for return values of the 'status' variable.
Followng is a .js file deployed, and the offending function in question is codeAddress(). Similar code to codeAddress() works elsewhere online that I can find, so it must be something to do with the circumstances under which its being called. Given that the map displays just fine, and I can place markers, my expectation is that my session is just fine. This leaves me puzzled :( Does anyone know what 'ERROR' could come from??
var map;
var marker;
var geocoder;
function placeMarker(location) {
if (!marker) {
marker = new google.maps.Marker({
position: location,
map: map
});
} else {
marker.setPosition(location);
}
map.setCenter(location);
var field = document.getElementById("portCreate:coordinate");
field.value = "POINT (" + location.lat() + " " + location.lng() + ")";
}
function initialize() {
var mapOptions = {
center : new google.maps.LatLng(55.761123, 13.084717),
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById("map"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
setMarker(document.getElementById("portCreate:coordinate"));
geocoder = new google.maps.Geocoder();
}
function setMarker(field) {
if (field.value) {
var regex = /POINT.+?([-0-9\.]+).+?([-0-9\.]+)/;
var matches = regex.exec(field.value);
placeMarker(new google.maps.LatLng(Number(matches[1]), Number(matches[2])));
}
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status + "\nFor address " + address);
}
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?key=<API key here>&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
After having this same problem today I've remembered that instead of doing a link to the API I downloaded the code as .js. After changing it to a link it works agains. I think Google updates the script regurlaly, if it had any version conflict they return the ERROR status.
The documentation for javascript/geocoding shows 'ERROR' as a possible result:
"ERROR" indicates that the request timed out or there was a problem contacting the Google servers. The request may succeed if you try again.
I had the same problem. I was working with ASP .Net application. After I changed the ASP .Net button control to HTML input Button, it is working now. Not sure where the problem is.
<input type="button" value="Geocode" onclick="codeAddress()">
I was troubleshooting a similar issue, where I was able to recreate the ERROR status by canceling the google API http request before it returned a response.
Users search my map with the Google places API which adds markers to my map. I have a click event inside each markers infowindow to get directions to that marker.
How do I pass the coordinates of the selected marker to my google directions service request?
So far I declared var placeLoc = null; as a global variable. I defined placeLoc=place.geometry.location; inside my create marker function. Then I have:
function calcRoute() {
var start = myLatLng;
var end = placeLoc;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.BICYCLING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
The function renders directions to the wrong marker. I am guessing that it is just giving directions to the first marker in the array returned after the search and not the actual marker I selected. How do I provide the directions request the coordinates of a selected marker?
Below is the code that places the search results into the place variable:
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
// alert("getPlaces returns "+places.length+" places");
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var place = places[i];
createMarker(place);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
// if (markers.length == 1) map.setZoom(17);
});
Something like this?
function createMarker(options) {
var marker = new google.maps.Marker(options);
google.maps.event.addListener(marker, 'click', function() {
placeLoc = marker.getPosition();
calcRoute();
});
return marker;
}