2013-04-05 33 views
0
poly = new google.maps.Polyline(polyOptions); 
poly.setMap(map); 

google.maps.event.addListener(map, 'click', addLatLng); 

function addLatLng(event) { 

    var path = poly.getPath(); 

    // Because path is an MVCArray, we can simply append a new coordinate 
    // and it will automatically appear 
    path.push(event.latLng); 

    // Add a new marker at the new plotted point on the polyline. 
    var marker = new google.maps.Marker({ 
     position: event.latLng, 
     title: '#' + path.getLength(), 
     map: map, 
     dragable: false, 
     clickable: true, 
     name: name, 
     raiseOnDrag: false, 
    }); 

    //This event is fired when setAt() is called. The event passes the index that was passed to setAt() and the element that was previously in the array at that index. 
    google.maps.event.addListener(path, 'set_at', function(index,oldWP) {     
     //called when editing the path 
     //we need to remove the (current) marker and add a new one at the position 

    }); 

    google.maps.event.addListener(path, 'insert_at', function(index) { 
     //when insert happens not at the end of the path but somewhere in the middle 
     //We need to completely rerender all makers 

    }); 
} 

Google文檔:當調用setAt()時會觸發此事件。該事件傳遞傳遞給setAt()的索引以及之前位於該索引處數組中的元素。set_at在Google Maps V3 API中多次調用

然而這個事件被稱爲x次(其中x是路徑的#elem)。

任何人都知道這是爲什麼,如果這可以防止(保持記憶計數器)。

+0

是什麼觸發了事件(path.push()不會做,所以必須有別的什麼修改路徑) – 2013-04-05 10:36:53

+0

我編輯的代碼;因此每次點擊都會調用addLatLng;這應該發生;但將addLatLng函數之外的事件偵聽器置於無效狀態。有任何想法嗎? – Thomas 2013-04-05 11:15:55

+1

在函數之外聲明路徑,並且您將能夠在函數之外添加偵聽器 – 2013-04-05 11:43:02

回答

0

你在這裏做的是你每次路徑改變時都向路徑添加新的監聽器。你想要做的只是添加一次監聽器。我想這應該做的伎倆:

poly = new google.maps.Polyline(polyOptions); 
poly.setMap(map); 
var path = poly.getPath(); 

google.maps.event.addListener(map, 'click', addLatLng); 

function addLatLng(event) { 

    // Because path is an MVCArray, we can simply append a new coordinate 
    // and it will automatically appear 
    path.push(event.latLng); 

    // Add a new marker at the new plotted point on the polyline. 
    var marker = new google.maps.Marker({ 
     position: event.latLng, 
     title: '#' + path.getLength(), 
     map: map, 
     dragable: false, 
     clickable: true, 
     name: name, 
     raiseOnDrag: false, 
    }); 
} 

//This event is fired when setAt() is called. The event passes the index that was passed to setAt() and the element that was previously in the array at that index. 
google.maps.event.addListener(path, 'set_at', function(index,oldWP) {     
    //called when editing the path 
    //we need to remove the (current) marker and add a new one at the position 

}); 

google.maps.event.addListener(path, 'insert_at', function(index) { 
    //when insert happens not at the end of the path but somewhere in the middle 
    //We need to completely rerender all makers 

});