绘制多段线类似于DrawingManager中多段线的绘制

Drawing polyline similar to drawing of polyline in DrawingManager

这是我在点击地图上的第一个点后绘制多段线的方式,在点击地图上的第二个点后绘制多段线canvas:

Sample google.maps.Polyline

这是使用 DrawingManager 绘制折线的方式:

Sample Drawing Manager

我想以与 DrawingManager 相同的方式绘制我的常规多段线,其中继续显示我在地图上移动鼠标的位置 canvas。

谢谢,

您可以使用地图鼠标悬停事件实现此目的。这 returns 一个 LatLng,比如 pointA。如果您可以编写代码来记录您之前绘制的点,比如 pointB,那么您可以在此事件中呈现一条从 pointA 到 pointB 的不同样式的临时线。

如果您想要代码示例,请告诉我。

这对我有用,一个重要的细节是在构建折线时指定 clickable: false,否则它不会在地图上注册点击事件。

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Complex Polylines</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
var poly;
var map;
var existingPolylinePath;
var tempPoly;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {lat: 41.879, lng: -87.624}  // Center the map on Chicago, USA.
  });

  poly = new google.maps.Polyline({
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3,
    map: map,
    clickable: false
  });

  tempPoly = new google.maps.Polyline({
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 3,
    map: map,
    clickable: false
  });

  // Add a listener for the click event
  map.addListener('click', addLatLng);

  map.addListener('mousemove', function(event) {
    existingPolylinePath = poly.getPath();

    if (existingPolylinePath.length > 0) {
        tempPoly.setPath([existingPolylinePath.getAt(existingPolylinePath.length - 1), event.latLng]);
    }
  });
}

// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
  var path = poly.getPath();

  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear.
  path.push(event.latLng);

  // Add a new marker at the new plotted point on the polyline.
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
}
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
  </body>
</html>