首页 > 解决方案 > 单击时添加折线并在鼠标光标上显示下一个点

问题描述

不知道如何在标题中表达我的问题,但我想做的是有一个功能,当您单击“画一条线”时,它的行为与您的地点 -> 地图 -> 在 maps.google.com 上创建地图相同" -> "添加线条或形状" 按钮。它在地图上开始一条折线,然后显示一条从该点到鼠标光标的阴影线,这样当您再次单击时,您可以看到您的线是什么:

在此处输入图像描述

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');
}

小提琴

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

标签: javascriptgoogle-mapsgoogle-maps-api-3

解决方案


向地图添加mousemove事件侦听器。使用它来设置折线的第二个(或下一个)顶点。

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');
}

概念证明小提琴

代码片段:

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>


推荐阅读