2013-10-25 91 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); 
    }); 
});