Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Google Maps viewport to automatically fit pane for locations of (n) markers of various locations

The approach I took thus far has been:

function addMarker( query ) {
    var geocoder = new google.maps.Geocoder();
    var afterGeocode = $.Deferred();

    // Geocode 'query' which is the address of a location.
    geocoder.geocode( 
            { address: query }, 
            function( results, status ){

                    if( status === 'OK' ){
                        afterGeocode.resolve( results ); // Activate deferred.
                    }
            }
    );

    afterGeocode.then( function( results ){
        var mOptions = {
            position: results[0].geometry.location,
            map: map
        }

        // Create and drop in marker.
        var marker = new google.maps.Marker( mOptions );
        marker.setAnimation( google.maps.Animation.DROP );      

        var current_bounds = map.getBounds(); // Get current bounds of map
        // use the extend() function of the latlngbounds object
        // to incorporate the location of the marker
        var new_bounds = current_bounds.extend( results[0].geometry.location );
        map.fitBounds( new_bounds ); // fit the map to those bounds
    }); 
}

The problem I'm running into is that the map inexplicably zooms out by some amount, no matter if the new marker fits within the current viewport or not.

What am I doing wrong?

ADDENDUM

I added logs and an additional variable to capture the map bounds after the transition was made (new_new_bounds)

current_bounds = // Map bounds before anything is done.
    {-112.39575760000002, 33.60691883366427},
    {-112.39295444655761, 33.639099}

new_bounds = // From after the extend
    {-112.39295444655761, 33.60691883366427}, 
    {-112.39575760000002, 33.639099}

new_new_bounds = // From after the fitbounds
    {-112.33942438265382, 33.588697452015374},
    {-112.44928766390382, 33.657309727063996}
like image 782
dclowd9901 Avatar asked May 13 '11 20:05

dclowd9901


1 Answers

OK, so after much wrangling, it turns out that the problem was a map's bounds are not the same as a map's bounds after fitBounds(). What happens (I presume), is Google takes the bounds you give it in the fitBounds() method, and then pads them. Every time you send the current bounds to fitBounds(), You're not going to fit bounds(x,y), you're going to fit bounds(x+m,y+m) where m = the arbitrary margin.

That said, the best approach was this:

var current_bounds = map.getBounds();
var marker_pos = marker.getPosition();

if( !current_bounds.contains( marker_pos ) ){

    var new_bounds = current_bounds.extend( marker_pos );
    map.fitBounds( new_bounds );
}

So, the map will only fit bounds if a marker placed falls outside the current map bounds. Hope this helps anyone else who hits this problem.

like image 192
dclowd9901 Avatar answered Oct 27 '22 00:10

dclowd9901