10

I want to save the current position where to user is watching and restore back after some clicks.

How do I get the current lat longitude bounds so that I could map.fitBounds on it?

  • This thread has a better anser, to avoid multiple fires [Click to go to answer](http://stackoverflow.com/questions/4338490/google-map-event-bounds-changed-triggered-multiple-times-when-dragging) – Arun Prasad E S Apr 29 '17 at 16:55

2 Answers2

8

getBounds() in Google Maps API v3

So to get our latitude and longitude we need to move getBounds() to bounds_changed event listener.

     var map = new google.maps.Map(document.getElementById("map"), {
             zoom: 10,
             center: new google.maps.LatLng(lat, lng),
             mapTypeId: google.maps.MapTypeId.ROADMAP
     });
     google.maps.event.addListener(map, 'bounds_changed', function() {
              var bounds =  map.getBounds();
              var ne = bounds.getNorthEast();
              var sw = bounds.getSouthWest();
              console.log(ne.lat());
              console.log(ne.lng());
              console.log(sw.lat());
              console.log(sw.lng());
     });

This event is fired when the viewport bounds have changed. If you have some ajax call in it, every time position of map changes the ajax call will be fired.

So, the better solution in that case is to move getBounds() in idle event listener. This event is fired when the map becomes idle after zooming.

     var map = new google.maps.Map(document.getElementById("map"), {
             zoom: 10,
             center: new google.maps.LatLng(lat, lng),
             mapTypeId: google.maps.MapTypeId.ROADMAP
      });
     google.maps.event.addListener(map, 'idle', function() {
              var bounds =  map.getBounds();
              var ne = bounds.getNorthEast();
              var sw = bounds.getSouthWest();
              console.log(ne.lat());
              console.log(ne.lng());
              console.log(sw.lat());
              console.log(sw.lng());
     });
Vivek Kumar
  • 2,625
  • 2
  • 25
  • 33
8

Here's the code to capture the current map bounds, on the "bounds_changed" event

google.maps.event.addListener(map, 'bounds_changed', function() {
        try {
            if( initialBounds == null ) {
                initialBounds = map.getBounds(); 
            }
        } catch( err ) {
            alert( err );
        }
    });

Then, you can return the map the bound using this code

google.maps.event.addDomListener(controlUI, 'click', function() {
        // map.setCenter(home)
        if( initialBounds != null ) {
            map.fitBounds( initialBounds );
        }
    });
William Walseth
  • 2,803
  • 1
  • 23
  • 25