What I want to do is load a bunch of addresses using AJAX and JSON, find out the latitude and longitude of each address, put markers on the map and then use fitBounds()
to zoom in so that all markers are visible. Sounds simple.
I've got most of that down packed but my issue is the fitBounds()
part.
Basically what seems to be occurring is while looping through each of the addresses and finding the latitude and longitude, it seems to load the fitBounds()
function below the loop.
So it's calling fitBounds()
but doesn't have anything in the marker_bounds
array yet. I would have thought it would have finished looping before getting to the fitBounds()
function but I guess the geocoder.geocode()
function must cause it to continue loading the rest of the JavaScript while it determines a latitude and longitude.
My code is below:
var geocoder;
var map;
var marker_bounds = [];
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.post('addresses.php', function(data) {
var next_filter = '';
for(var x=0;x<data.addresses.length;x++) {
geocoder.geocode( { 'address': data.addresses[x].address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var latLng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker_bounds.push(latLng);
}
});
}
var latlngbounds = new google.maps.LatLngBounds();
for ( var i = 0; i < marker_bounds.length; i++ ) {
latlngbounds.extend(marker_bounds[i]);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
}, 'json');
Is there a function that I can call after all geocoding has been completed?