如何获得折线上最近的标记?

How to get the nearest marker on the polyline?

当我将鼠标移到折线上时,我需要获得最近的标记。 标记位于同一条折线上。 标记是隐藏的,我想显示离鼠标最近的一个,然后显示下一个并隐藏前一个。 谢谢

    // SET PATH 
      var Path = new google.maps.Polyline({
        geodesic: true,
        strokeColor: '#993300',
        strokeOpacity: 1.0,
        strokeWeight: 4 ,
        id: 123
      });
      Path.setMap(map);

      var path = Path.getPath();
      data.map(function(val){
        path.push(new google.maps.LatLng(+val.lat, +val.lon));
        Path.setPath(path);
      })

google.maps.event.addListener(Path, 'mousemove',function(e){
  console.log(e.latLng)
})

首先,您需要确保在加载 google 地图时需要加载 geometry 库 JavaScript API.

<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
</script>

然后,当您将鼠标悬停在您的多段线上时,在您的标记上循环并获得从鼠标悬停点到所有标记的距离(因为在您检查所有标记之前您不知道哪一个是最近的)。

这是一种方法:

//your markers in an array
var markers = [];

google.maps.event.addListener(polyline,'mouseover',function(e) {
     var closestMarker;
     markers.reduce(function(carry,marker) {
        var d = google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(),e.latLng);

       if(d < carry || carry == -1) {
           closestMarker = marker;
           return d;
       }

       return carry;

    },-1);

   //your marker is now in the variable closestMarker
});

您可以使用 Google Maps JavaScript API marker methods

轻松了解如何隐藏和显示标记