1. 程式人生 > >openlayers限制地圖拖動區域

openlayers限制地圖拖動區域

現在做webgis基本都會用到openlayers或者leaflet。那麼在顯示地圖的時候,特別是顯示小區域地圖的時候,由於地圖區域較小,就會存在把地圖拖動到顯示區域之外的現象。那麼該如何限制地圖拖動的區域呢。

    在openlayers2中有restrictedExtent屬性,直接設定下即可。

[javascript] view plain copy
  1. var options = {  
  2.             controls : [  
  3.                         new OpenLayers.Control.Navigation()  
  4.                         ],  
  5.             projection: new OpenLayers.Projection("EPSG:4326"),  
  6.             maxResolution: 0.703125,  
  7.            // minScale:1/3500,
  8. //            minScale:100,
  9.             numZoomLevels :22 ,  
  10.             restrictedExtent: restrictedExtent,  
  11.             //maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90),
  12.             //allOverlays : true
  13.     };  
  14.     //初始化map物件
  15.     this.map = new OpenLayers.Map('map',options);  

但是在openlayers3中,由於沒有直接的屬性和介面使用,因此需要用別的方法。我用的方法就是在map的view物件中新增extent屬性來限制。


[javascript] view plain copy
  1. map.setView(new ol.View({  
  2.             center: mapCenter,  
  3.             projection: this.projection,  
  4.             //extent : mapExtent,
  5.             zoom: 18,  
  6.             minZoom: 16,  
  7.             maxZoom: 23,  
  8.             extent:[mapExtent[1]-0.0001,mapExtent[0]-0.0001,mapExtent[3]+0.0001,mapExtent[2]+0.0001]  
  9.         }));