gpt4 book ai didi

javascript - 如何防止在谷歌地图上平移外部世界边缘?

转载 作者:行者123 更新时间:2023-12-02 23:35:30 25 4
gpt4 key购买 nike

我首先说我已经看过很多这样的答案,并且 this one是越来越近的东西。

所以基本上我做到了:

    var defaultLatLong = {
lat: 45.4655171,
lng: 12.7700794
};

var map = new google.maps.Map(document.getElementById('map'), {
center: defaultLatLong,
zoom: 3,
minZoom: 3,
restriction: {
latLngBounds: {
east: 180,
north: 85,
south: -85,
west: -180
},
strictBounds: true
}, ...

但这会阻止在左/右平移时进行顶部/底部平移。

知道为什么吗?

UDPATE

我尝试了以下方法:

    var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(85, 180),
new google.maps.LatLng(-85, -180)
);
var lastValidCenter = map.getCenter();

google.maps.event.addListener(map, 'center_changed', function() {
if (allowedBounds.contains(map.getCenter())) {
// still within valid bounds, so save the last valid position
lastValidCenter = map.getCenter();
return;
}
// not valid anymore => return to last valid position
map.panTo(lastValidCenter);
});

但是当它停止水平平移时,我无法平移到两极,所以顶部/底部

最佳答案

根据the documentation :

A restriction that can be applied to the Map. The map's viewport will not exceed these restrictions.

latLngBounds

Type: LatLngBounds|LatLngBoundsLiteral
When set, a user can only pan and zoom inside the given bounds. Bounds can restrict both longitude and latitude, or can restrict latitude only. For latitude-only bounds use west and east longitudes of -180 and 180, respectively. For example,
latLngBounds: {north: northLat, south: southLat, west: -180, east: 180}

将经度限制设置为非 -180/+180。

proof of concept fiddle

代码片段:

function initMap() {
var defaultLatLong = {
lat: 45.4655171,
lng: 12.7700794
};

var map = new google.maps.Map(document.getElementById('map'), {
center: defaultLatLong,
zoom: 3,
minZoom: 3,
restriction: {
latLngBounds: {
east: 179.9999,
north: 85,
south: -85,
west: -179.9999
},
strictBounds: true
}
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

关于javascript - 如何防止在谷歌地图上平移外部世界边缘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56306243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com