以下是我的Google Maps javascript文件的完整代码。我要做的是首先初始化地图,然后动态添加标记并刷新地图。
// GLOBALS
var map;
function refreshMap() {
google.maps.event.trigger(map,'resize');
map.setCenter(map.get('originalCenter'));
}
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
scrollwheel: false,
center: new google.maps.LatLng(56.4611388, -2.9719832),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
originalCenter: new google.maps.LatLng(56.4611388, -2.9719832)
}
map = new google.maps.Map(map_canvas, map_options)
}
// Initialise Map
google.maps.event.addDomListener(window, 'load', initialize);
// Add a Marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(56.4611388, -2.9719832),
map: map,
title: 'Marker'
});
// Refresh
refreshMap();
运行refreshMap()
时出现以下错误:
Uncaught TypeError: Cannot read property '__e3_' of undefined main.js:15
这是刷新地图的正确方法吗?
答案 0 :(得分:1)
您的代码当前运行的方式是设置初始化函数以在页面加载事件触发时运行,然后创建标记(由于页面加载事件未触发,映射尚未初始化),然后调用refreshMap(再次在页面加载事件之前,因此映射仍未初始化)。单击该按钮时,下面的代码会触发refreshMap函数,但在加载页面并运行初始化函数之前,它无法运行。
// GLOBALS
var map;
function refreshMap() {
google.maps.event.trigger(map, 'resize');
map.setCenter(map.get('originalCenter'));
}
// this function runs on the page load event after the DOM has been rendered
// and both the map_canvas and btn elements exist.
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
scrollwheel: false,
center: new google.maps.LatLng(56.4611388, -2.9719832),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
originalCenter: new google.maps.LatLng(56.4611388, -2.9719832)
};
map = new google.maps.Map(map_canvas, map_options);
// need do do this in the initialize function, after the page has loaded and the 'btn' exists
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function () {
// Add a Marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(56.4611388, -2.9719832),
map: map,
title: 'Marker'
});
// Refresh
refreshMap();
});
}
// Initialize Map
google.maps.event.addDomListener(window, 'load', initialize);