gpt4 book ai didi

javascript - 缩放至搜索(标记)位置 Google Maps API

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

当我搜索地址时,我希望我的 map 能够缩放到搜索(标记)位置。我一直在浏览论坛并找到建议,但我无法让它发挥作用。

代码示例

function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 52.0, lng: 1.0}
});
var geocoder = new google.maps.Geocoder();

document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
}

function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);

var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});

map.setZoom(14);
map.panTo(Marker.position);

}
else {
alert('clever text here: ' + status);
}
});

任何想法将不胜感激。

最佳答案

geocodeAddress() 函数内的 setZoom(14) 不起作用,因为您从不正确的 map 对象引用调用了它。您应该调用 resultsMap.setZoom(14) 而不是 map.setZoom(14)。

"map" 变量在函数 initMap() 内声明,并在调用 geocodeAddress() 函数时作为参数传递:geocodeAddress(geocoder, map).

现在在geocodeAddress()的方法定义中, map 对象引用改为"resultsMap"参数名称:function geocodeAddress(geocoder, resultsMap) {...}。这就是为什么您必须在 geocodeAddress() 函数内使用 resultsMap.setZoom(14) 的原因。

这是 JSFiddle 中的工作示例.

希望这有帮助!

关于javascript - 缩放至搜索(标记)位置 Google Maps API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55262010/

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