I have created a function that will create a markers array with places obtained by using the Places API. The type parameter is used for the place type, and the icon is used for the marker icon.
function setPOIMarkerArray(type, icon) {
var array = new Array();
var request = {
location: map.getCenter(),
radius: '2000',
types: [type]
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (i in results) {
place = results[i];
var marker = new google.maps.Marker({
icon: icon,
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng())
});
google.maps.event.addListener(marker, 'click', function() {
var content = '<img class="left-arrow-grocery" src="/img/leftArrow.png"><div class="grocery-infobox">' + place.name + '<br/>' + place.vicinity + '</div>';
ib.setContent(content);
ib.open(map, marker);
});
array.push(marker);
}
return array;
}
});
}
When I call this code using the $(function(){});, in which I set up my map and other stuff, I call var groceryStores = setPOIMarkerArray('grocery_or_supermarket','grocery.png')
but the groceryStores array ends up being empty if I console.log(groceryStores)
If I console.log(array) inside the setPOIMarkerArray it does show the results.
I believe this is due to the fact that the code doesn’t wait for the response to come back from the google API. What can I do to fix this, or what is the problem? Thanks
The
searchfunction is performed asynchronously, so thearraywill only have the marker added to it after the response is received. The browser performs this request in the background and doesn’t wait for it to respond, that is why the array is empty directly after the function is called.EDIT: You don’t need to do anything to overcome it. It’s doing what it’s supposed to do. However, if you want to be notified when the response is returned from the search, you can add a function call in your callback.
Example: Display an alert when a marker is added.
function marker_added() { alert('marker added'); }