2016-12-19 19 views
0

我正在試驗谷歌地圖,並試圖將一些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); 
+0

時被調用DrawLine的? (initMaps可能尚未被調用......) –

+0

它應該在正文的javascript塊中調用。 – user3713442

+0

觸發'drawLine()'的任何事情都不應該發生,直到調用了initMap()。你的其他JavaScript塊是什麼樣的? –

回答

0

內我想您一定的競爭問題:

var marker 1;//var init 
drawLine();//draw line called, marker isnt set yet 
initMap(); //map ready 

解決方案1: 鎖的drawLine(),直到initMap完成

var mapready=false; 
function initMap(){ 
//your code 
mapready=true; 
} 
function drawLine(){ 
if(!mapready){return false;} 
//your code 
} 

這是一個很好的解決方案,如果drawLine可以由我們引起呃。

解決方案2A:在地圖inited 調用的drawLine:

function initMap(){ 
//your code 
drawLine(); 
} 

解決方案2B: 解決方案,如果你想動態調用的drawLine(有時,有時不)是心不是很好。 比這將是很好註冊回調:

mapready=[]; 
function initMap(){ 
//your init code 




//map is ready so call callbacks 
for(i=0;i<mapready.length;i++){ 
mapready[i](); 
} 
//if an callback is added now, fire it directly 
mapready={}; 
mapready.push=function(func){func();}; 
} 

要添加的回調:

mapready.push(drawLine); 
+0

謝謝 - 它變成了一個競賽條件。在頁面加載3秒後,我對DrawLine()進行了測試setTimeout調用,以便完成地圖初始化並繪製線條。 這也解決了我有的其他問題,但它看起來像我需要重構我有什麼。 地圖初始化完成後,解決方案2是否會觸發回調函數?這聽起來就像我需要的,但我對回調不太熟悉。 – user3713442

+0

是的,它表現了你的想法。當mapinit完成或者稍後添加它時,將觸發回調(示例中爲drawLine) –