谷歌地理编码服务
我正在尝试使用 Google 地理编码器服务来获取用户输入的城市坐标。但是,初始化 LatLng() 对象 (latlngCity) 时似乎出现一些问题,并且地图不会显示。代码如下:
var map;
var latlngCity;
function initialize() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': 'Lisbon, PT'}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
latlngCity = results[0].geometry.location;
}
});
var myMapOptions = {
zoom: 8,
center: latlngCity,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myMapOptions);
}
为了简单起见,我自己插入地址城市字符串。变量 map 和 latlngCity 是全局变量。这段代码有什么问题吗? 非常感谢。
I'm trying to use Google geocoder service to get the coordinates of cities input by the user. However looks like there's some problem initializing the LatLng() object (latlngCity), and the map won't show up. The code is as following:
var map;
var latlngCity;
function initialize() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': 'Lisbon, PT'}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
latlngCity = results[0].geometry.location;
}
});
var myMapOptions = {
zoom: 8,
center: latlngCity,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myMapOptions);
}
For simplicity, I'm inserting the address city string myself. Variables map and latlngCity are globals. Is there anything wrong with this code?
Thanks very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将地图创建代码移至
geocode
回调中(或者使用某些默认位置创建地图,然后在回调内重新将地图居中)。在您的代码中,在创建地图时,
latlngCity
尚未定义,而geocode
仍在执行(异步)。希望这是有道理的。否则我会提供一些代码。让我知道。
You need to move the map creation code into the
geocode
callback (or alternatively create the map with some default position and then re-center the map inside the callback).In your code,
latlngCity
is undefined by the time of map creation whilegeocode
is still being executed (asynchronously).Hope this makes sense. Otherwise I'll provide some code. Let me know.