JavaScript & Google Maps v3: capture result of tilesloaded() event?
I have a problem with Javascript's asychronous nature, and Google M开发者_JAVA百科aps. I'm adding some markers to a map using the Google Maps V3 tilesloaded
listener.
I don't know how to get hold of these markers so I can later do things with them, because tilesloaded fires asynchronously, and I'm a Javascript newbie!
Here's the code:
function show_place () {
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = addMarker(lat, lng);
markers.push(marker);
// When the map boundaries move, add new markers within the bounds.
google.maps.event.addListener(map, 'tilesloaded', function() {
var bounds = map.getBounds();
$.getJSON("/markers_within_bounds/", { [variables] }, function(json){
for (i=0;i<json.length;i++) {
var map_marker = addMarker(json[i].lat, json[i].lng);
markers.push(map_marker); //Try to add markers to the array. Fail.
}
});
});
return markers;
}
$(document).ready(function() {
var markers = show_place(lat, lng);
alert(markers.length);
// Do things with the markers... if there is more than 1.
});
The alert always shows 1, because show_place
is returning BEFORE it loads all the markers. I can't get hold of the extra markers that have been added.
How can I get round this?
Thanks.
You should do that like this:
var marker = new google.maps.Marker({
position: point,
title: 'mytitle'
});
marker.setMap(myMap);
markersArray.push(marker);
You may already have the markers in the variable, but when you request a length in
$(document).ready(function ...)
the length will always be one (1) because you inserted the marker, the inner function only fires after the tiles have been loaded all the while the show_place() has finished executing. Your show_place() shouldn't return anything. However, if you wanted to alert the user that you uploaded the data, you would put the code within the inner "Callback" function or call a declared function within the callback function block.
1- I think you can make a public variable instead on returning a value from your function.
2- Please check inside the firebug console to see is there any problem.
3- instead of using tilesloaded, you can use idle or bounds_changed(better to avoid since the google call this event many times)
var markerList = [];
function (data){//AJAX CALLBACK FUNCTION
//EMPTY THE LIST & CLEAR THE MARKER FROM MAP
for (var i = 0; i < markerList.length; i++) {
markerList[i].setMap();
};
markerList.length = 0;
markerList[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(data[i].geo_latitude, data[i].geo_longitude),
title: data[i].fn
});
};
精彩评论