谷歌地图API V3:在单击折线事件的两个现有点之间添加点。

4

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

2个回答

6

如果您只是在谈论仅有2个点的Polyline,您可以使用包含PolylineLatLngBounds的中心。然而,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;
};

当一条线只有2个点时,Polyline.getBounds()将包含包括此线的区域。这个边界框的中心应该是您的线的准确中心。如果Polyline包含超过2个点,则中心不会落在所点击的线的中心上,而是包括所有点的边界框的中心。如果要在此函数中使用多段Polyline,则需要进行更多的数学计算以确定所单击的线段。以下是一个使用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>

0

你只需要计算方位和距离的50% - 然后加上垂直线。

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

你可能需要一个临时边界对象,它通过前一个和下一个顶点latlang来扩展边界。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接