代码之家  ›  专栏  ›  技术社区  ›  Tomik

谷歌地图v3-限制可视区域和缩放级别

  •  91
  • Tomik  · 技术社区  · 14 年前

    有没有可能将googlemapv3限制在某个区域?我希望只允许显示某个区域(例如国家),不允许用户在其他地方滑动。我还想限制缩放级别-例如,仅在级别6和9之间。我想使用所有的底图类型。

    有没有办法做到这一点?

    通过使用StyledMap限制缩放级别,我取得了部分成功,但是我只成功地限制了ROADMAP,我无法通过这种方式限制其他基本类型的缩放。

    谢谢你的帮助

    12 回复  |  直到 14 年前
        1
  •  120
  •   Tushar Gupta - curioustushar    10 年前

    你可以听听 dragend 事件,如果将贴图拖到允许的边界之外,请将其移回内部。您可以在 LatLngBounds 对象,然后使用 contains() 检查新lat/lng中心是否在界限内的方法。

    您还可以很容易地限制缩放级别。

    考虑以下示例: Fiddle Demo

    <!DOCTYPE html>
    <html> 
    <head> 
       <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
       <title>Google Maps JavaScript API v3 Example: Limit Panning and Zoom</title> 
       <script type="text/javascript" 
               src="http://maps.google.com/maps/api/js?sensor=false"></script>
    </head> 
    <body> 
       <div id="map" style="width: 400px; height: 300px;"></div> 
    
       <script type="text/javascript"> 
    
       // This is the minimum zoom level that we'll allow
       var minZoomLevel = 5;
    
       var map = new google.maps.Map(document.getElementById('map'), {
          zoom: minZoomLevel,
          center: new google.maps.LatLng(38.50, -90.50),
          mapTypeId: google.maps.MapTypeId.ROADMAP
       });
    
       // Bounds for North America
       var strictBounds = new google.maps.LatLngBounds(
         new google.maps.LatLng(28.70, -127.50), 
         new google.maps.LatLng(48.85, -55.90)
       );
    
       // 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));
       });
    
       // Limit the zoom level
       google.maps.event.addListener(map, 'zoom_changed', function() {
         if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
       });
    
       </script> 
    </body> 
    </html>
    

    Google Maps JavaScript API v3 Example: Force stop map dragging

        2
  •  184
  •   martin    8 年前

    minZoom / maxZoom

    var opt = { minZoom: 6, maxZoom: 9 };
    map.setOptions(opt);
    

    var map = new google.maps.Map(document.getElementById('map-canvas'), opt);
    

    请参见: Google Maps JavaScript API V3 Reference

        3
  •  18
  •   Community kfsone    4 年前

    好消息。从2019年2月14日发布的MapsJavaScriptAPI版本3.35开始,您可以使用新的 restriction 选项以限制地图的视口。

    MapRestriction接口

    可以应用于地图的限制。地图的视口将不会超过这些限制。

    资料来源: https://developers.google.com/maps/documentation/javascript/reference/map#MapRestriction

    var map;
    function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 46.818188, lng: 8.227512},
        minZoom: 7,
        maxZoom: 14,
        zoom: 7,
        restriction: {
          latLngBounds: {
            east: 10.49234,
            north: 47.808455,
            south: 45.81792,
            west: 5.95608
          },
          strictBounds: true
        },
      });
    }
    #map {
      height: 100%;
    }
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap" async defer></script>

    我希望这有帮助!

        4
  •  6
  •   kleopatra Aji kattacherry    11 年前

    限制v.3+上的缩放。 缩放级别为0到19。

    function initialize() {
       var mapOptions = {
          maxZoom:17,
          minZoom:15,
          zoom:15,
          ....
    
        5
  •  3
  •   Pat    13 年前

    var dragStartCenter;
    
    google.maps.event.addListener(map, 'dragstart', function(){
                                           dragStartCenter = map.getCenter();
                                             });
    
    google.maps.event.addListener(this.googleMap, 'dragend', function(){
                                if (mapBounds.contains(map.getCenter())) return;
                        map.setCenter(this.dragStart);
                               });
    
        6
  •  1
  •   Jonathan Busuttil    10 年前

    这可用于将地图重新居中到特定位置。这正是我需要的。

        var MapBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(35.676263, 13.949096),
        new google.maps.LatLng(36.204391, 14.89038));
    
        google.maps.event.addListener(GoogleMap, 'dragend', function ()
        {
            if (MapBounds.contains(GoogleMap.getCenter()))
            {
                return;
            }
            else
            {
                GoogleMap.setCenter(new google.maps.LatLng(35.920242, 14.428825));
            }
        });
    
        7
  •  1
  •   Anup    9 年前
    myOptions = {
            center: myLatlng,
            minZoom: 6,
            maxZoom: 9,
            styles: customStyles,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
        8
  •  0
  •   Alexander Palamarchuk    12 年前

            google.maps.event.addListener(this.map, 'idle', function() {
                var minLat = strictBounds.getSouthWest().lat();
                var minLon = strictBounds.getSouthWest().lng();
                var maxLat = strictBounds.getNorthEast().lat();
                var maxLon = strictBounds.getNorthEast().lng();
                var cBounds  = self.map.getBounds();
                var cMinLat = cBounds.getSouthWest().lat();
                var cMinLon = cBounds.getSouthWest().lng();
                var cMaxLat = cBounds.getNorthEast().lat();
                var cMaxLon = cBounds.getNorthEast().lng();
                var centerLat = self.map.getCenter().lat();
                var centerLon = self.map.getCenter().lng();
    
                if((cMaxLat - cMinLat > maxLat - minLat) || (cMaxLon - cMinLon > maxLon - minLon))
                {   //We can't position the canvas to strict borders with a current zoom level
                    self.map.setZoomLevel(self.map.getZoomLevel()+1);
                    return;
                }
                if(cMinLat < minLat)
                    var newCenterLat = minLat + ((cMaxLat-cMinLat) / 2);
                else if(cMaxLat > maxLat)
                    var newCenterLat = maxLat - ((cMaxLat-cMinLat) / 2);
                else
                    var newCenterLat = centerLat;
                if(cMinLon < minLon)
                    var newCenterLon = minLon + ((cMaxLon-cMinLon) / 2);
                else if(cMaxLon > maxLon)
                    var newCenterLon = maxLon - ((cMaxLon-cMinLon) / 2);
                else
                    var newCenterLon = centerLon;
    
                if(newCenterLat != centerLat || newCenterLon != centerLon)
                    self.map.setCenter(new google.maps.LatLng(newCenterLat, newCenterLon));
            });
    

    strictBounds new google.maps.LatLngBounds() self.gmap 存储Google地图对象( new google.maps.Map() ).

    它确实有效,但不要忘了考虑到痔疮与交叉第0经络和平行线,如果你的边界覆盖他们。

        9
  •  0
  •   Mayko    12 年前

    因为某种原因

    if (strictBounds.contains(map.getCenter())) return;
    

    不适合我(可能是南半球的问题)。我不得不把它改成:

        function checkBounds() {
            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 > maxX || y < minY || y > maxY) {
                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));
            }
        }
    

    希望它能帮助别人。

        10
  •  0
  •   Adam    10 年前

    一种解决方案是,如果你知道具体的lat/lng。

    google.maps.event.addListener(map, 'idle', function() {
    
        map.setCenter(new google.maps.LatLng(latitude, longitude));
        map.setZoom(8);
    
    });
    

    如果没有具体的lat/lng

    google.maps.event.addListener(map, 'idle', function() {
    
        map.setCenter(map.getCenter());
        map.setZoom(8);
    
    });
    

    google.maps.event.addListener(map, 'idle', function() {
    
        var bounds = new google.maps.LatLngBounds();
        map.setCenter(bounds.getCenter());
        map.setZoom(8);
    
    });
    
        11
  •  0
  •   Matej P.    8 年前

    截至2016年年中

    enter image description here

    为了解决这个问题,我创建了一个 library ,它成功地限制了边界,因此无法平移出覆盖。

    然而,与其他现有解决方案一样,它也存在一个“振动”问题。当用户足够积极地平移地图时,在他们释放鼠标左键后,地图仍会继续自己平移,逐渐变慢。我总是将贴图返回到边界,但这会导致某种振动。这种平移效果目前无法用jsapi提供的任何方法停止。似乎在谷歌增加对地图.stopPanningAnimation()我们无法创造一个流畅的体验。

    示例使用上述库,我能够获得的最平滑的严格边界体验:

    function initialise(){
      
      var myOptions = {
         zoom: 5,
         center: new google.maps.LatLng(0,0),
         mapTypeId: google.maps.MapTypeId.ROADMAP,
      };
      var map = new google.maps.Map(document.getElementById('map'), myOptions);
      
      addStrictBoundsImage(map);
    }
    
    function addStrictBoundsImage(map){
    	var bounds = new google.maps.LatLngBounds(
    		new google.maps.LatLng(62.281819, -150.287132),
    		new google.maps.LatLng(62.400471, -150.005608));
    
    	var image_src = 'https://developers.google.com/maps/documentation/' +
    		'javascript/examples/full/images/talkeetna.png';
    
    	var strict_bounds_image = new StrictBoundsImage(bounds, image_src, map);
    }
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
          <script type="text/javascript">
            google.load("maps", "3",{other_params:"sensor=false"});
          </script>
    <body style="margin:0px; padding:0px;" onload="initialise()">
    	 <div id="map" style="height:400px; width:500px;"></div>
         <script  type="text/javascript"src="https://raw.githubusercontent.com/matej-pavla/StrictBoundsImage/master/StrictBoundsImage.js"></script>
    </body>

    minZoom 地图的属性。

    希望这能帮助那些想要一个完全尊重给定边界的解决方案的人,并且不想允许平移它们。

        12
  •  -4
  •   Chris Page    11 年前

    这可能会有帮助。

      var myOptions = {
          center: new google.maps.LatLng($lat,$lang),
          zoom: 7,
          disableDefaultUI: true,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };