我使用Google Maps API(v3)渲染世界地图。当我一直缩放(缩放级别1)并开始拖动画布时,我可以移出地图边界,外面的区域显示为灰色。我想阻止用户在世界地图边界之外拖动地图。我该怎么做?
答案 0 :(得分:2)
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(0,0);
var myOptions = {
zoom: 1,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.addListener( 'drag', function() { handle(); });
//map.addListener( 'zoom_changed', function() { handle(); });
}
function handle(){
var proj = map.getProjection();
var bounds = map.getBounds();
var sLat = map.getBounds().getSouthWest().lat();
var nLat = map.getBounds().getNorthEast().lat();
if (sLat < -85 || nLat > 85) {
// alert('Gray area visible');
map.setOptions({
zoom: 1,
center: new google.maps.LatLng(
0 , // set Latitude for center of map here
0) // set Langitude for center of map here
});
//Map.fitBounds(boundsNew);
// Or Define bound that u want show
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer src="https://maps.googleapis.com/maps/api/js">
</script>
</head>
<body onload="initialize()" >
<div id="map_canvas" style="width:500px;height:500px;"></div>
</body></html>
答案 1 :(得分:0)
我知道这个问题已经很老了,但是我一直在寻找答案并找到了这篇文章。
我认为我的答案可能是对被接受的答案的改进。
将地图移回灰色区域的边缘,而不是将用户送回到任意中心。
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(0,0);
var myOptions = {
zoom: 1,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.addListener( 'drag', function() { handle(); });
//map.addListener( 'zoom_changed', function() { handle(); });
}
function handle(){
var bounds = map.getBounds();
var center = map.getCenter();
var sLat = bounds.getSouthWest().lat();
var nLat = bounds.getNorthEast().lat();
var cLat = center.lat();
var cLng = center.lng();
if (sLat < -85) {
map.setOptions({
center: new google.maps.LatLng(
cLat + ((sLat + 85) * -1),
cLng
)
)};
}
if (nLat > 85) {
map.setOptions({
center: new google.maps.LatLng(
cLat - nLat + 85,
cLng
)
)};
}
}
希望这可以帮助某人。
答案 2 :(得分:0)
Google Maps api具有相应的选项: https://developers.google.com/maps/documentation/javascript/reference/map#MapRestriction.latLngBounds。需要添加类似的内容:
restriction: {
latLngBounds: { north: 85, south: -85, west: -180, east: 180 }
}
转到地图的初始选项。
答案 3 :(得分:-4)
您可以设置minZoom和maxZoom以确保可用的缩放级别在您的范围内,希望有帮助吗?