Вопрос

Я пытаюсь установить границы на моей карте, чтобы представить только определенную часть города. Мой текущий код:

     var strictBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(42.340, -71.20), 
     new google.maps.LatLng(42.370, -71.0)
   );

var mapOptions = 
{
    maxZoom:19,
    minZoom:15,
};

handler = Gmaps.build('Google', {markers: { maxRandomDistance: null} });
handler.buildMap({ provider: mapOptions, internal: {id: 'map'}}, function(){
  markers = handler.addMarkers(<%=raw @hash.to_json %>);
  handler.bounds.extendWith(markers);
  handler.fitMapToBounds();
  handler.getMap().setCenter(new google.maps.LatLng(42.359, -71.090413));
});

   // Listen for the dragend event
   google.maps.event.addListener(map, 'dragend', function() {
     if (strictBounds.contains(map.getCenter())) return;

     // We're out of bounds - Move the map back within the bounds

     var c = map.getCenter(),
         x = c.lng(),
         y = c.lat(),
         maxX = strictBounds.getNorthEast().lng(),
         maxY = strictBounds.getNorthEast().lat(),
         minX = strictBounds.getSouthWest().lng(),
         minY = strictBounds.getSouthWest().lat();

     if (x < minX) x = minX;
     if (x > maxX) x = maxX;
     if (y < minY) y = minY;
     if (y > maxY) y = maxY;

     map.setCenter(new google.maps.LatLng(y, x));
   });
.

Однако границы вообще не работают, и пользователь может пойти в любом месте на карте.Любые идеи, что я делаю не так?

Это было полезно?

Решение

Порядок вещей в вашем скрипте кажется действительно странным, делать:

var southWest = new google.maps.LatLng( 42.340, -71.20 );
var northEast = new google.maps.LatLng( 42.370, -71.0 );
var hyderabadBounds = new google.maps.LatLngBounds( southWest, northEast );
var mapOptions = 
{
    maxZoom:19,
    minZoom:15,
    bounds: hyderabadBounds
};

handler = Gmaps.build('Google', {markers: { maxRandomDistance: null} });
handler.buildMap({ provider: mapOptions, internal: {id: 'map'}}, function(){
  markers = handler.addMarkers(<%=raw @hash.to_json %>);
  handler.bounds.extendWith(markers);
  handler.fitMapToBounds();
  handler.getMap().setCenter(new google.maps.LatLng(42.359, -71.090413));
});
.

BTW, нет параметра bounds в Google Maps, см. Док

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top