I've got the following code which gets the list of addresses from php script, then makes an ajax request to google maps, then creates markers and changes the zoom to fit the markers.
var bounds = new google.maps.LatLngBounds();
$.getJSON('/dmvfinder/dmvsearch.php', {zipcode: zipcode, state: state, city: city}, function (addresses) {
addresses.forEach(function(address){
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json', {address: address}, function(data){
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
bounds.extend(latlng);
});
});
});
map.fitBounds(bounds);
As far as i understand the problem with the code is that the fitBounds method fires before ajax finishes and the 'bounds' gets filled. How could i possibly defer the last line of code here?
Thank you in advance!