4

如何在单击折线事件的两个现有点之间的折线上添加点?谢谢!

4

2 回答 2

6

如果您只是在谈论Polyline只有 2 个点的 a,您可以使用LatLngBounds包含 的a 的中心Polyline。不过, Google maps api v3 并未实现该Polyline.getBounds()功能。因此,您可以扩展Polyline该类以包含一个getBounds函数:

google.maps.Polyline.prototype.getBounds = function() {
  var bounds = new google.maps.LatLngBounds();
  this.getPath().forEach(function(e) {
    bounds.extend(e);
  });
  return bounds;
};

Polyline.getBounds()在只有 2 个点的线上将包含包含该线的区域。这个边界的中心应该是你的线的确切中心。如果Polyline包含超过 2 个点,则中心不会落在单击的线的中心,而是位于包含所有点的边界的中心。如果您想在此函数中使用多段折线,则需要更多的数学计算来计算单击了哪个段。

这是一个使用 2 点的小例子Polyline

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Right in Two</title>

    <style type="text/css">
      #map-canvas {
        height: 500px;
      }
    </style>

    <script type="text/javascript"
        src="http://www.google.com/jsapi?autoload={'modules':[{name:'maps',version:3,other_params:'sensor=false'}]}"></script>
    <script type="text/javascript">

      function init() {
        var mapDiv = document.getElementById('map-canvas');
        var map = new google.maps.Map(mapDiv, {
          center: new google.maps.LatLng(37.790234970864, -122.39031314844),
          zoom: 5,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var points = [
                  new google.maps.LatLng(40.785533,-124.16748),
                  new google.maps.LatLng(32.700413,-115.469971)
        ];

        var line = new google.maps.Polyline({
          map: map,
          path: points,
          strokeColor: "#FF0000",
          strokeWeight: 2,
          strokeOpacity: 1.0
        });

        google.maps.Polyline.prototype.getBounds = function() {
          var bounds = new google.maps.LatLngBounds();
          this.getPath().forEach(function(e) {
            bounds.extend(e);
          });
          return bounds;
        };

        google.maps.event.addListener(line, 'click', function(e){
          var marker = new google.maps.Marker({
            map: map,
            position: line.getBounds().getCenter()
          });
        });

      };

      google.maps.event.addDomListener(window, 'load', init);
    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>
于 2010-08-23T15:58:43.447 回答
0

您只需要计算方位角和 50% 的距离 - 在此处添加垂直。

上面的例子是边界的中心 - 这是相同的。

您可能需要一个临时边界对象,该对象通过上一个和下一个 verticle latlang 扩展边界。

于 2011-04-17T00:00:26.410 回答