Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API V3: limit map bounds [duplicate]

I'm trying to set bounds where you can drag the map using Google Maps API V3 Here is the solution for V2 http://econym.org.uk/gmap/example_range.htm that works pretty well.

However with API V3 it isn't so good: when you use the same checkbounds() function, the map is twitching when you reach the bound while map.setCenter() changes the center of the map.

How to fix it? What is the solution for API V3?

like image 691
Ekaterina Prigara Avatar asked Oct 10 '10 18:10

Ekaterina Prigara


1 Answers

I've had the same problem, but this should sort it out (it's the same function, the event to listen to is changed from 'move' or 'drag' to 'center_changed', works like a charm!:

google.maps.event.addListener(map,'center_changed',function() { checkBounds(); });

function checkBounds() {    
    if(! allowedBounds.contains(map.getCenter())) {
      var C = map.getCenter();
      var X = C.lng();
      var Y = C.lat();

      var AmaxX = allowedBounds.getNorthEast().lng();
      var AmaxY = allowedBounds.getNorthEast().lat();
      var AminX = allowedBounds.getSouthWest().lng();
      var AminY = allowedBounds.getSouthWest().lat();

      if (X < AminX) {X = AminX;}
      if (X > AmaxX) {X = AmaxX;}
      if (Y < AminY) {Y = AminY;}
      if (Y > AmaxY) {Y = AmaxY;}

      map.setCenter(new google.maps.LatLng(Y,X));
    }
}
like image 68
sairafi Avatar answered Sep 23 '22 07:09

sairafi