Google Maps v3 - 如何在初始化时使用地址居中? [英] Google Maps v3 - How to center using an address on initialize?
问题描述
使用 Google Maps API v3,有没有办法在初始化时设置地图的中心?我有一个使用此代码的解决方法:
Using Google Maps API v3, is there a way to set the center of the map on initialize? I have a workaround using this code:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
codeAddress('germany');
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
}
唯一的问题是,当它初始化时,它会在一瞬间将它集中到latlng".我不知道如何在myOptions"中设置中心.我虽然可以从 codeAddress 函数返回results[0].geometry.location"并将其传递给 myOptions,但这不起作用.
The only problem is that when it initializes, it centers it to the "latlng" for a split second. I'm can't figure out how to set the center in "myOptions". I though I could return "results[0].geometry.location" from the codeAddress function and pass it to myOptions, but that doesn't work.
感谢您的帮助.
更新由于我无法完全删除中心",我想知道是否有办法将地址传递给选项.
Update Since I can't remove "center" altogether, I'm wondering if there's a way to pass the address to the options.
来自 Google API:
From Google API:
要初始化 Map,我们首先创建一个 Map 选项对象来包含地图初始化变量.这个对象不是构造的;相反,它被创建为对象字面量.有两个必填每个地图的选项:center 和 zoom.
To initialize a Map, we first create a Map options object to contain map initialization variables. This object is not constructed; instead it is created as an object literal. There are two required options for every map: center and zoom.
推荐答案
嗯,一个简单的解决方案可能是在 codeAddress 函数中初始化地图:
Well a simple solution could be to initialize the map in your codeAddress function:
var geocoder, map;
function codeAddress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 8,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
}
这应该可以解决问题.
这篇关于Google Maps v3 - 如何在初始化时使用地址居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!