尝试一下:
//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;
此外:你永远不应该使用这些无证属性,如mb
或lb
,这些属性的名称不固定,可能会在未来会议上改变。
我注意到你没有在click中嵌套mousemove事件。嵌套事件监听器通常是一个坏主意吗? – Skitterm
我不会这么说(只要你正确地使用它们,并在冗余时清除它们) –