绘制折线,类似于DrawingManager中折线的绘制

时间:2016-01-07 17:03:17

标签: google-maps-api-3 polyline

这是我在单击第一个点时绘制折线的方法,在点击地图画布上的第二个点后绘制折线:

Sample google.maps.Polyline

如何使用DrawingManager绘制折线:

Sample Drawing Manager

我希望以与DrawingManager绘制的方式相同的方式绘制常规折线,其中该线继续显示我将鼠标移动到地图画布上的位置。

谢谢,

2 个答案:

答案 0 :(得分:1)

这对我有用,一个重要的细节是在构造折线时指定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>

答案 1 :(得分:0)

你可以使用map mouseover事件实现这一点。这返回一个LatLng,比如pointA。如果您可以编写将记录您绘制的上一个点的代码,例如pointB,那么您可以在此事件中渲染从pointA到pointB的临时行。

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

相关问题