gpt4 book ai didi

javascript - map.setCenter() 函数无法正常工作

转载 作者:数据小太阳 更新时间:2023-10-29 04:22:28 27 4
gpt4 key购买 nike

这是代码...

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var geocoder;
var map;

function initialize() {
geocoder = new google.maps.Geocoder();
var address = "new delhi";

geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
alert(latitude);
alert(longitude);
map.setCenter(new GLatLng(latitude, longitude));

var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var latlng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
});
google.maps.event.addDomListener(window, 'load', initialize);
}
</script>

最佳答案

你需要像这样设置中心...

map.setCenter(new google.maps.LatLng(latitude, longitude));

此外,您在初始化 map 之前设置了中心,因此会引发错误。

Demo Fiddle

这是更新后的 JS。

     var geocoder;

var map;

function initialize() {

geocoder = new google.maps.Geocoder();

var address = "new delhi";

geocoder.geocode({
'address': address
}, function (results, status) {

if (status == google.maps.GeocoderStatus.OK) {

var latitude = results[0].geometry.location.lat();

var longitude = results[0].geometry.location.lng();

alert(latitude);

alert(longitude);




var latlng = new google.maps.LatLng(latitude, longitude);

var mapOptions = {

zoom: 8,

center: latlng,

mapTypeId: google.maps.MapTypeId.ROADMAP

}

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

var latlng = new google.maps.LatLng(latitude, longitude);
map.setCenter(latlng);

var marker = new google.maps.Marker({

map: map,

position: latlng,
title: 'Hello World!'

});
}

});
}
google.maps.event.addDomListener(window, 'load', initialize);

关于javascript - map.setCenter() 函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19537225/

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