javascript - 如何根据沿线的距离在 Google map 折线上添加标记?

标签 javascript google-maps distance intervals polyline

我正在尝试创建一个 Google map ,用户可以在其中绘制他步行/运行/骑自行车的路线,并查看他跑了多长时间。 GPolyline 类及其 getLength() 方法在这方面非常有用(至少对于 Google Maps API V2),但我想添加基于距离的标记,因为例如 1 公里、5 公里、10 公里等的标记,但似乎没有明显的方法可以根据沿线的距离在折线上找到一个点。有什么建议吗?

最佳答案

拥有answered a similar problem几个月前,关于如何在 SQL Server 2008 的服务器端解决这个问题,我正在使用 Google Maps API v2 将相同的算法移植到 JavaScript。 .

为了这个例子,让我们使用一条简单的 4 点折线,总长度约为 8,800 米。下面的代码片段将定义这条折线并将其呈现在 map 上:

var map = new GMap2(document.getElementById('map_canvas'));

var points = [
   new GLatLng(47.656, -122.360),
   new GLatLng(47.656, -122.343),
   new GLatLng(47.690, -122.310),
   new GLatLng(47.690, -122.270)
];

var polyline = new GPolyline(points, '#f00', 6);

map.setCenter(new GLatLng(47.676, -122.343), 12);
map.addOverlay(polyline);

现在,在我们接近实际算法之前,我们需要一个函数,该函数在给定起点、终点和沿该线行进的距离时返回目的地点,幸运的是,有一些方便的 JavaScript 实现Chris Veness 在 Calculate distance, bearing and more between Latitude/Longitude points .

特别是,我从上述源代码中采用了以下两种方法来处理 Google 的 GLatLng 类:

这些用于通过 moveTowards() 方法扩展 Google 的 GLatLng 类,当给定另一个点和以米为单位的距离时,它将返回另一个 GLatLng 当距离从原始点到作为参数传递的点行进时沿着该线。

GLatLng.prototype.moveTowards = function(point, distance) {   
   var lat1 = this.lat().toRad();
   var lon1 = this.lng().toRad();
   var lat2 = point.lat().toRad();
   var lon2 = point.lng().toRad();         
   var dLon = (point.lng() - this.lng()).toRad();

   // Find the bearing from this point to the next.
   var brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
                         Math.cos(lat1) * Math.sin(lat2) -
                         Math.sin(lat1) * Math.cos(lat2) * 
                         Math.cos(dLon));

   var angDist = distance / 6371000;  // Earth's radius.

   // Calculate the destination point, given the source and bearing.
   lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) + 
                    Math.cos(lat1) * Math.sin(angDist) * 
                    Math.cos(brng));

   lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
                            Math.cos(lat1), 
                            Math.cos(angDist) - Math.sin(lat1) *
                            Math.sin(lat2));

   if (isNaN(lat2) || isNaN(lon2)) return null;

   return new GLatLng(lat2.toDeg(), lon2.toDeg());
}

有了这个方法,我们现在可以按如下方式解决问题:

  1. 遍历路径的每个点。
  2. 找出迭代中的当前点与下一个点之间的距离。
  3. 如果点 2 的距离大于我们需要在路径上行驶的距离:

    ...那么目标点就在这一点和下一点之间。只需将 moveTowards() 方法应用于当前点,传递下一个点和要移动的距离。返回结果并中断迭代。

    否则:

    ...目标点距离迭代中的下一个点更远。我们需要从沿路径行进的总距离中减去这一点和下一点之间的距离。使用修改后的距离继续迭代。

您可能已经注意到,我们可以轻松地以递归方式而不是迭代方式实现上述内容。那么让我们开始吧:

function moveAlongPath(points, distance, index) {
   index = index || 0;  // Set index to 0 by default.

   if (index < points.length) {
      // There is still at least one point further from this point.

      // Construct a GPolyline to use its getLength() method.
      var polyline = new GPolyline([points[index], points[index + 1]]);

      // Get the distance from this point to the next point in the polyline.
      var distanceToNextPoint = polyline.getLength();

      if (distance <= distanceToNextPoint) {
         // distanceToNextPoint is within this point and the next. 
         // Return the destination point with moveTowards().
         return points[index].moveTowards(points[index + 1], distance);
      }
      else {
         // The destination is further from the next point. Subtract
         // distanceToNextPoint from distance and continue recursively.
         return moveAlongPath(points,
                              distance - distanceToNextPoint,
                              index + 1);
      }
   }
   else {
      // There are no further points. The distance exceeds the length  
      // of the full path. Return null.
      return null;
   }  
}

使用上述方法,如果我们定义一个 GLatLng 点数组,并使用这个点数组调用我们的 moveAlongPath() 函数,距离为 2,500米,它将在距第一个点 2.5 公里处的路径上返回 GLatLng

var points = [
   new GLatLng(47.656, -122.360),
   new GLatLng(47.656, -122.343),
   new GLatLng(47.690, -122.310),
   new GLatLng(47.690, -122.270)
];

var destinationPointOnPath = moveAlongPath(points, 2500);

// destinationPointOnPath will be a GLatLng on the path 
// at 2.5km from the start.

因此,我们需要做的就是为路径上需要的每个检查点调用moveAlongPath()。如果您需要在 1km、5km 和 10km 处设置三个标记,您可以简单地执行以下操作:

map.addOverlay(new GMarker(moveAlongPath(points, 1000)));
map.addOverlay(new GMarker(moveAlongPath(points, 5000)));
map.addOverlay(new GMarker(moveAlongPath(points, 10000)));

但是请注意,如果我们请求距离路径总长度更远的检查点,moveAlongPath() 可能会返回 null,因此检查在将值传递给 new GMarker() 之前返回值。

我们可以将其放在一起以进行全面实现。在这个例子中,我们沿着前面定义的 8.8 公里路径每 1,000 米放置一个标记:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps - Moving point along a path</title> 
   <script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
           type="text/javascript"></script> 
</head> 
<body onunload="GUnload()"> 
   <div id="map_canvas" style="width: 500px; height: 300px;"></div>

   <script type="text/javascript"> 

   Number.prototype.toRad = function() {
      return this * Math.PI / 180;
   }

   Number.prototype.toDeg = function() {
      return this * 180 / Math.PI;
   }

   GLatLng.prototype.moveTowards = function(point, distance) {   
      var lat1 = this.lat().toRad();
      var lon1 = this.lng().toRad();
      var lat2 = point.lat().toRad();
      var lon2 = point.lng().toRad();         
      var dLon = (point.lng() - this.lng()).toRad();

      // Find the bearing from this point to the next.
      var brng = Math.atan2(Math.sin(dLon) * Math.cos(lat2),
                            Math.cos(lat1) * Math.sin(lat2) -
                            Math.sin(lat1) * Math.cos(lat2) * 
                            Math.cos(dLon));

      var angDist = distance / 6371000;  // Earth's radius.

      // Calculate the destination point, given the source and bearing.
      lat2 = Math.asin(Math.sin(lat1) * Math.cos(angDist) + 
                       Math.cos(lat1) * Math.sin(angDist) * 
                       Math.cos(brng));

      lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angDist) *
                               Math.cos(lat1), 
                               Math.cos(angDist) - Math.sin(lat1) *
                               Math.sin(lat2));

      if (isNaN(lat2) || isNaN(lon2)) return null;

      return new GLatLng(lat2.toDeg(), lon2.toDeg());
   }

   function moveAlongPath(points, distance, index) {        
      index = index || 0;  // Set index to 0 by default.

      if (index < points.length) {
         // There is still at least one point further from this point.

         // Construct a GPolyline to use the getLength() method.
         var polyline = new GPolyline([points[index], points[index + 1]]);

         // Get the distance from this point to the next point in the polyline.
         var distanceToNextPoint = polyline.getLength();

         if (distance <= distanceToNextPoint) {
            // distanceToNextPoint is within this point and the next. 
            // Return the destination point with moveTowards().
            return points[index].moveTowards(points[index + 1], distance);
         }
         else {
            // The destination is further from the next point. Subtract
            // distanceToNextPoint from distance and continue recursively.
            return moveAlongPath(points,
                                 distance - distanceToNextPoint,
                                 index + 1);
         }
      }
      else {
         // There are no further points. The distance exceeds the length  
         // of the full path. Return null.
         return null;
      }  
   }

   var map = new GMap2(document.getElementById('map_canvas'));

   var points = [
      new GLatLng(47.656, -122.360),
      new GLatLng(47.656, -122.343),
      new GLatLng(47.690, -122.310),
      new GLatLng(47.690, -122.270)
   ];

   var polyline = new GPolyline(points, '#f00', 6);

   var nextMarkerAt = 0;     // Counter for the marker checkpoints.
   var nextPoint = null;     // The point where to place the next marker.

   map.setCenter(new GLatLng(47.676, -122.343), 12);

   // Draw the path on the map.
   map.addOverlay(polyline);

   // Draw the checkpoint markers every 1000 meters.
   while (true) {
      // Call moveAlongPath which will return the GLatLng with the next
      // marker on the path.
      nextPoint = moveAlongPath(points, nextMarkerAt);

      if (nextPoint) {
         // Draw the marker on the map.
         map.addOverlay(new GMarker(nextPoint));

         // Add +1000 meters for the next checkpoint.
         nextMarkerAt += 1000;    
      }
      else {
         // moveAlongPath returned null, so there are no more check points.
         break;
      }            
   }
   </script>
</body> 
</html>

上述示例的屏幕截图,每 1,000 米显示一个标记:

Google Maps - Move Point Along a Path

关于javascript - 如何根据沿线的距离在 Google map 折线上添加标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2698112/

相关文章:

algorithm - 距离矩阵的近似估计

google-maps - 从 google map api v3 获取英文地址

android - 如何使用标记在android中显示 map

javascript - 使用jquery选择按下回车时的下一个字段

javascript - XSLT if 语句不正确匹配

javascript - 融合表值未正确返回

r 行间距离

iphone - 计算iphone中两点之间的距离

javascript - 为什么我在 switch 语句中得到不同的结果

javascript - 检查每个元素并根据父元素更改它 (JavaScript/jQuery)