我是 google maps api 的新手。我从手册中获取了一些示例并尝试按照我需要的方式对其进行更改,所以这是我正在尝试做的事情: 这是谷歌地图手册中的例子
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng( 40.714353, -74.005973);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
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
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
我稍微更改了 codeAddress 函数并尝试在页面加载时调用它,如下所示:
function codeAddress(address) {
//var address = document.getElementById("address").value;
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
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
codeAddress("Some Address");
但它给我一个 javascript 错误“地理编码器未定义”。如何让脚本等到 map 加载完毕后再运行 codeAddress 函数?我不想在初始化期间设置我的地址路径。
我希望这是清楚的 提前谢谢你。
最佳答案
问题是您在定义 codeAddress
之后直接调用它(因此这是在 initialise()
方法运行之前。
因此,您需要稍后在某个触发器上运行它。一种快速而肮脏的方法是将其设置为主体的 onload
事件;这将等到所有资源(包括图像)都已完全加载,但考虑到 map 也是图像,这可能不是什么大问题。
或者,大多数 JS 框架会为您提供非常方便的方法,以在页面生命周期的不同时间点触发您的处理程序。如果您正在使用其中之一,您可能希望调查可用的选项并选择最佳选项,这取决于多种因素。
重要的是,不要忘记在调用 codeAddress()
之前必须调用 initialise()
!
关于javascript - 新手问题 : How to get information if google map is loaded (initialized),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4193959/