【问题标题】:Drawing polyline similar to drawing of polyline in DrawingManager绘制折线类似于在 DrawingManager 中绘制折线
【发布时间】:2016-04-12 04:34:46
【问题描述】:

这就是我在单击第一个点的位置绘制多段线的方式,然后在单击地图画布上的第二个点后绘制多段线:

Sample google.maps.Polyline

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

Sample Drawing Manager

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

谢谢,

【问题讨论】:

  • 到目前为止你的代码是什么样的?
  • 如果绘图管理器能满足您的需求,为什么不能使用它?您可以删除控件。
  • 我无法使用 DrawingManager,因为我的自定义折线具有绑定到它的标记和标签。

标签: google-maps-api-3 polyline


【解决方案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>

【讨论】:

  • 优秀。它与我的自定义折线中的 map mousemove 事件很好地配合使用。谢谢。
【解决方案2】:

您可以使用地图鼠标悬停事件来实现这一点。这将返回一个 LatLng,例如 pointA。如果您可以编写代码来记录您绘制的上一个点,例如 pointB,那么您可以在此事件中以不同样式渲染从 pointA 到 pointB 的临时线。

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

【讨论】:

  • 感谢您的建议。我将尝试使用 map mousemove 事件。如果我不能让它工作,我会告诉你的。
猜你喜欢
  • 2016-07-31
  • 2013-11-20
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多