2013-10-25 34 views
1

我已經創建了一個地圖,用戶可以在該地圖中單擊並拖動以將自由格式折線作爲多邊形的一部分。然而,我不能把它放到我能看到從我剛剛做出的那個點到你的光標所在的那條線的地方。我想要實現這個功能。點與光標之間的線

我目前正在使用click,mousemove等事件偵聽器進行自由格式折線,並且這些在繪圖庫下被禁用。

在繪製多邊形或多段線時,Maps Engine Lite從您剛點擊的位置繪製一條直線的方式如何?

我已經瀏覽了DrawingManager和DrawingOptions,無法弄清楚它是如何以編程方式顯示從點到光標的一條直線。

我猜我需要在mousemove上找到我的光標的座標,並在該位置和我點擊的最後一個點之間繪製一條線。它是否正確?

回答

3

嘗試一下:

//observe click 
    google.maps.event.addListener(map,'click',function(e){ 
     //if there is no Polyline-instance, create a new Polyline 
     //with a path set to the clicked latLng 
     if(!line){ 
      line=new google.maps.Polyline({map:map,path:[e.latLng],clickable:false}); 
     } 

     //always push the clicked latLng to the path 
     //this point will be used temporarily for the mousemove-event 
     line.getPath().push(e.latLng); 
     new google.maps.Marker({map:map,position:e.latLng, 
           draggable:true, 
           icon:{url:'http://maps.gstatic.com/mapfiles/markers2/dd-via.png', 
            anchor:new google.maps.Point(5,5)}}) 

    }); 
    //observe mousemove 
    google.maps.event.addListener(map,'mousemove',function(e){ 
     if(line){ 
     //set the last point of the path to the mousemove-latLng 
     line.getPath().setAt(line.getPath().getLength()-1,e.latLng) 
     } 
    }); 

演示:http://jsfiddle.net/doktormolle/4yPDg/

注:你的這部分代碼是多餘的:

var coord = new google.maps.LatLng(option.latLng.lb, option.latLng.mb); 

option.latLng已經是一個google.maps.LatLng,你可以使用它直接

var coord = option.latLng; 

此外:你永遠不應該使用這些無證屬性,如mblb,這些屬性的名稱不固定,可能會在未來會議上改變。

+0

我注意到你沒有在click中嵌套mousemove事件。嵌套事件監聽器通常是一個壞主意嗎? – Skitterm

+0

我不會這麼說(只要你正確地使用它們,並在冗餘時清除它們) –

0

我想出了一個可能的解決方案。它可能不是最優雅的。任何其他想法?

google.maps.event.addListener(map, 'click', function(option) { 
    var coord = new google.maps.LatLng(option.latLng.lb, option.latLng.mb); 

    var connector = new google.maps.Polyline(); 

    google.maps.event.addListener(map, 'mousemove', function(pt) { 
     connector.setMap(null); 
     document.getElementById('latlgn').innerHTML = pt.latLng; 

     var lineTwoPoints = [ 
      coord, 
      pt.latLng 
     ]; 
     connector.setPath(lineTwoPoints); 
     connector.setMap(map); 
    }); 
});