单击添加折线并显示鼠标光标上的下一个点

时间:2018-05-21 17:44:01

标签: javascript google-maps google-maps-api-3

不确定如何在标题中说出我的问题,但我想要做的是有一个与你的地方相同的功能 - >地图 - >单击“绘制线条”时在maps.google.com上创建地图 - > “添加线条或形状”按钮。它在地图上启动折线,然后显示从该点到鼠标光标的阴影线,这样您就可以看到再次点击时您的线条:

enter image description here

Google Maps API中是否有内置选项来执行此操作?到目前为止,当用户第一次点击地图时,我有这么多:

function startNewLine(latLng) {
  var line = new google.maps.Polyline({
    draggable: true,
    editable: true,
  });

  line.setMap(boundaryMap);
  line.getPath().push(latLng);

  google.maps.event.clearListeners(boundaryMap, 'click');
}

Fiddle

它在点击的位置开始一个新行,但这就是我所得到的。

1 个答案:

答案 0 :(得分:1)

向地图添加mousemove event listener。用它来设置折线的第二个(或下一个)顶点。

boundaryMap.addListener('mousemove', function(e) {
  if (line && line.getPath() && line.getPath().getLength() > 0)
    line.getPath().setAt(1, e.latLng);
});

对于多个顶点:

boundaryMap.addListener('mousemove', function(e) {
  console.log("mousemove " + e.latLng.toUrlValue(6));
  if (line && line.getPath() && line.getPath().getLength() > (nextV - 1))
    line.getPath().setAt(nextV, e.latLng);
})

function startNewLine(latLng) {
  line = new google.maps.Polyline({
    draggable: true,
    editable: true,
  });
  nextV = 1;
  line.setMap(boundaryMap);
  line.getPath().push(latLng);
  line.addListener('click', function(e) {
    nextV++;
    console.log("line click " + e.latLng.toUrlValue(6));
  })
  line.addListener('dblclick', function(e) {
    console.log("line dblclick " + e.latLng.toUrlValue(6));
    google.maps.event.clearListeners(boundaryMap, "mousemove");
  })
  google.maps.event.clearListeners(boundaryMap, 'click');
}

proof of concept fiddle

代码段

initMap();

var boundaryMap;
var line;
var nextV = 0;

function initMap() {
  boundaryMap = new google.maps.Map(document.getElementById("mapContainer"), {
    center: {lat: 37.1, lng: -95.7},
    zoom: 5
  });

  boundaryMap.addListener('click', function(e) {
    console.log("click " + e.latLng.toUrlValue(6));
    startNewLine(e.latLng);
  });
  boundaryMap.addListener('mousemove', function(e) {
    console.log("mousemove " + e.latLng.toUrlValue(6));
    if (line && line.getPath() && line.getPath().getLength() > (nextV - 1))
      line.getPath().setAt(nextV, e.latLng);
  })
}

function startNewLine(latLng) {
  line = new google.maps.Polyline({
    draggable: true,
    editable: true,
  });
  nextV = 1;
  line.setMap(boundaryMap);
  line.getPath().push(latLng);
  line.addListener('click', function(e) {
    nextV++;
    console.log("line click " + e.latLng.toUrlValue(6));
  })
  line.addListener('dblclick', function(e) {
    console.log("line dblclick " + e.latLng.toUrlValue(6));
    google.maps.event.clearListeners(boundaryMap, "mousemove");
  })
  google.maps.event.clearListeners(boundaryMap, 'click');
}
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="mapContainer" style="height: 100%; width: 100%;"></div>