我正在試驗谷歌地圖,並試圖將一些polyLines動起來。基本上,在文檔的主體中,我有一個setInterval函數,它會週期性地放置一段時間,然後在經過一段時間後擦除它們。問題來自於訪問各種地圖變量,但是當我嘗試並調用測試程序(如下所示)時,出現「marker1未定義」等錯誤。是否可以從地圖初始化例程之外訪問地圖變量?谷歌地圖變量和函數的範圍
這裏是Javascript代碼 - 這是所有頭
var commsLine = [];
var marker1, marker2, marker3, map, Comms;
function initMap() {
latLng = new google.maps.LatLng(50.8917,-1.3989);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: latLng,
mapTypeId: google.maps.MapTypeId.HYBRID,
scaleControl: true
});
marker1 = new google.maps.Marker({
position: new google.maps.LatLng(50.8917, 0),
map: map
});
marker2 = new google.maps.Marker({
position: new google.maps.LatLng(50.8917, -1.5),
map: map
});
marker3 = new google.maps.Marker({
position: new google.maps.LatLng(51.5, 0),
map: map
});
// DrawLine(); works when placed here but I want to call it from the
// setInterval function in the body
}
function DrawLine()
{
commsLine.push(marker1.getPosition());
commsLine.push(marker2.getPosition());
Comms = new google.maps.Polyline({
path: commsLine,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
Comms.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initMap);
時被調用DrawLine的? (initMaps可能尚未被調用......) –
它應該在正文的javascript塊中調用。 – user3713442
觸發'drawLine()'的任何事情都不應該發生,直到調用了initMap()。你的其他JavaScript塊是什麼樣的? –