javascript map.setCenter() 函数工作不正常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19537225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
map.setCenter() function is not working properly
提问by analyticalpicasso
Here's code...
这是代码...
<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>
回答by nik
You'll need to set center like this...
你需要像这样设置中心...
map.setCenter(new google.maps.LatLng(latitude, longitude));
Also you are setting center before initializing map and so its throwing an error.
您还在初始化地图之前设置中心,因此会引发错误。
Here's updated JS.
这是更新的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);
回答by Kishor Pawar
I am using gmaps.js library.
我正在使用 gmaps.js 库。
I was getting maximum stack size exceeded error when i tried to recenter the map using map.setCenter(new google.maps.LatLng(latitude, longitude));
当我尝试使用 map.setCenter(new google.maps.LatLng(latitude, longitude)); 重新定位地图时,出现最大堆栈大小超出错误;
so i tried just this map.setCenter(latitude, longitude); and it worked for me.
所以我只试过这个 map.setCenter(latitude, longitude); 它对我有用。