gpt4 book ai didi

google-maps - 如何使谷歌地图可拖动并将标记保持在屏幕中央?

转载 作者:行者123 更新时间:2023-12-04 08:18:42 25 4
gpt4 key购买 nike

我有一个按钮可以启用/禁用 map 的可拖动选项。

当用户拖动 map 时,我需要将标记保持在 map 的中心。

var map;

function toggleMapDraggable() {
if (map.get("draggable")) {
map.set("draggable", false);
} else {
map.set("draggable", true);
}
}

function initialize() {

var locations = [
['WELWYN GARDEN CITY ', 51.805616, -0.192647, 2],
['STANMORE  ', 51.603199, -0.296803, 1]
];

map = new google.maps.Map(document.getElementById('map_canvas'), {
navigationControl: true,
scrollwheel: false,
scaleControl: false,
draggable: false,
zoom: 10,
center: new google.maps.LatLng(51.75339, -0.210114),
mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();
var image = 'http://maps.google.com/mapfiles/ms/micons/blue.png';

var marker, i;


for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: image,
zIndex: 10
});

window.google.maps.event.addListener(map , 'drag', function (event) {
marker.setPosition( map .getCenter() );
});

google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" value="toggle draggable" onclick="toggleMapDraggable();" />
<div id="map_canvas"></div>

最佳答案

对于可拖动,您应该使用 setOptions

map.setOptions({draggable: true});

和中心的标记
 marker.setPosition( map.getCenter(););

关于google-maps - 如何使谷歌地图可拖动并将标记保持在屏幕中央?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512261/

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