+-
google map V2:
自定义地图缩放范围:
控制地图的缩放级别范围需要重载GMapType的getMinimumResolution()和getMaximumResolution()方法。下面的代码将地图的缩放级别设置为12-16。
function setMapResolution() { //获取所有地图类型 var mapTypes = map.getMapTypes(); //对所有地图类型限制缩放级别 for(var i=0; i<mapTypes.length; i++) { mapTypes[i].getMinimumResolution = function() { return 12; }; mapTypes[i].getMaximumResulution = function() { return 16; }; } }
然后在加载地图后调用此函数就可以将地图的缩放级别限制为12-16。
自定义地图的显示范围:
限制地图的显示范围稍微复杂一些。首先使用GLatLngBounds定义一个地图的范围。在地图拖动或移动后判断地图的中心是否移出限制的范围。如果超出范围则移动地图到限制范围内。
//限制地图的显示范围 function checkMapBounds(map, mapRange) { if(map) { if(mapRange.contains(map.getCenter())) { return; } var center = map.getCenter(); var centerX = center.lng(); var centerY = center.lat(); var maxX = mapRange.getNorthEast().lng(); var maxY = mapRange.getNorthEast().lat(); var minX = mapRange.getSouthWest().lng(); var minY = mapRange.getSouthWest().lat(); if(centerX < minX) { centerX = minX; } if(centerX > maxX) { centerX = maxX; } if(centerY < minY) { centerY = minY; } if(centerY > maxY) { centerY = maxY; } map.panTo(new google.maps.LatLng(centerY, centerX)); } }
//设置地图显示范围 google.maps.Event.addListener(map, 'dragend', function(){ checkMapBounds(map, mapRangeBound); });
var minZoomLevel = 4; var map = new google.maps.Map(document.getElementById('map'), { zoom: minZoomLevel, center: new google.maps.LatLng(35.570335826274345, 106.53511059863281), mapTypeId: google.maps.MapTypeId.ROADMAP }); //自定义地图缩放范围 google.maps.event.addListener(map, 'zoom_changed', function() { if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel); }); //自定义地图的显示范围:中国区域内部 var strictBounds = new google.maps.LatLngBounds( new google.maps.LatLng(14.48003790418668, 66.28120434863283), new google.maps.LatLng(54.44617552862156, 143.71284497363283 )); google.maps.event.addListener(map, 'dragend', function() { if (strictBounds.contains(map.getCenter())) return; 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)); });