Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API v3 - fitBounds after multiple geocoder requests

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?

like image 604
Ben Sinclair Avatar asked Jan 17 '23 04:01

Ben Sinclair


1 Answers

Ok, here's what I've learned.

  1. The geocode method makes an asynchonous call so the page that the geocode method is in will finish long before the geocoder is done looking up addresses during that process.
  2. You need to call a function (addressBounds) after the geocode method is run and count how many addresses it has geocoded (address_count).
  3. Each time the addressBounds function is called, check to see if all addresses have been looked up (if (total_addresses == address_count)), then run the fitBounds() function.

My final code

var geocoder;
var map;
var markerBounds = [];  

var myOptions = {
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}   
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);    

google.maps.event.addListenerOnce(map, 'idle', function(){

    $.post('addresses.php', function(data) {

        var total_addresses = data.addresses.length;            
        var address_count = 0;
        for(var x=0;x<total_addresses;x++) {    

            geocoder.geocode( { 'address': data.addresses[x].address }, function(results, status) {

                address_count++;        

                if (status == google.maps.GeocoderStatus.OK) {

                    marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                    });

                    var infowindow = new google.maps.InfoWindow();
                    infowindow.setContent(address);
                    google.maps.event.addListener(marker, 'click', function() {
                        infowindow.open(map, marker);
                    });

                    var myLatLng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());                      
                    addressesBounds(total_addresses, address_count, myLatLng);  

                }

            });

        }

    }, 'json');

});

function addressesBounds(total_addresses, address_count, myLatLng) {

    markerBounds.push(myLatLng);

    // make sure you only run this function when all addresses have been geocoded
    if (total_addresses == address_count) {
        var latlngbounds = new google.maps.LatLngBounds();
        for ( var i = 0; i < markerBounds.length; i++ ) {
           latlngbounds.extend(markerBounds[i]);
        }
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);
    }
}
like image 181
Ben Sinclair Avatar answered May 06 '23 21:05

Ben Sinclair