当我搜索地址时,我希望我的地图缩放到搜索(标记)位置。我一直在浏览论坛并找到建议,但我无法让它发挥作用。
代码示例
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)无法正常工作,因为您已从错误的地图对象引用中调用它。你应该调用resultsMap.setZoom(14)而不是map.setZoom(14)。
"map"
变量在函数initMap()中声明,并在调用geocodeAddress()函数时作为参数传递:geocodeAddress(geocoder, map)
。
现在,在geocodeAddress()的方法定义中,地图对象引用更改为"resultsMap"
参数名称:function geocodeAddress(geocoder, resultsMap){...}
。这就是为什么你必须在geocodeAddress()函数中使用resultsMap.setZoom(14)
。
这是JSFiddle的工作样本。
希望这可以帮助!