Search code examples
google-maps-api-3geocodinggoogle-geocoding-api

How do I auto zoom to view multiple markers using the Google Geocoding API?


I'm using the Google Geocoding API to build a map that puts markers on whichever locations are requested. At the moment it auto-zooms to each location individually - how do I use fit Bounds to make it zoom to all the locations, i.e. if Sydney is input first, then London, how do I ask it to auto-zoom so the user can view both?

I'm very new to this so any advice welcome!

I've tried many different way to use bounds, fit Bounds, marker.length etc but none of it works or makes much sense to me.

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 45.1497, lng: 100.0943},
        zoom: 3
    });

    var geocoder = new google.maps.Geocoder()

    var step1 = location.href.split("?")[1].split("=")[1]
    $("#address1").val(step1);
    geocodeAddress1(geocoder, map);

    $(".steps").keypress(function() {
        if (event.which == 13) {
            geocodeAddress(geocoder, map);
        }
    })
};

var labelIndex = 0;

function geocodeAddress1(geocoder, resultsMap) {
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    var address = $("#address1").val();
        geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: resultsMap,
                label: labels[labelIndex++ % labels.length],
                position: results[0].geometry.location
            });
        } else {
            alert('Search not successful: ' + status);
            }
        })
};

function geocodeAddress(geocoder, resultsMap) {
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var nextstep = "#".concat(event.target.id);
    debugger;
    var address = $(nextstep).val();
        geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: resultsMap,
                label: labels[labelIndex++ % labels.length],
                position: results[0].geometry.location
            });
        } else {
            alert('Search not successful: ' + status);
            }
        })
};

Solution

  • You need to store all the markers/loations first in an array each time you click "Geocode", then call bounds.extend() for each location searched to contain the given point and lastly call resultsMap.fitBounds() to set the viewport to contain the given bounds.

    var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
    });
    
    markerCount++;
    markers[markerCount] = marker;
    
    // extend the bounds here to consider each location
    bounds.extend(results[0].geometry.location);
    // then call fitBounts()
    resultsMap.fitBounds(bounds);
    

    Here's a working sample in JSFiddle.

    Hope it helps!