谷歌地图折线:点击折线部分并返回 ID? [英] Google Maps polyline: Click on section of polyline and return ID?

查看:23
本文介绍了谷歌地图折线:点击折线部分并返回 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个谷歌地图 V3 折线.我可以检测整个多段线上的点击事件,但我可以对点击事件做更高级的事情吗?

I have a Google Maps V3 polyline. I can detect click events on the entire polyline, but can I do anything more advanced with the click event?

我想要做的是检测多段线的哪一部分被点击,并在警报中显示.

What I'd like to do is detect which section of the polyline has been clicked, and show this in an alert.

 routePath = new google.maps.Polyline({
     path: routeCoordinates,
     strokeColor: "#CC33FF",
     strokeWeight: 3
 });     
 routePath.setMap(map);
 google.maps.event.addListener(routePath, 'click', function() {
     alert(routePath);
     // TODO: display which section of the polyline has been clicked?
 });

有人知道如何在 Google 地图中执行此操作吗?

Does anyone know how to do this in Google Maps?

谢谢!

推荐答案

在单击事件上,您可以接收被单击坐标的 LatLng.但是,由于这可能不是创建折线的确切点,因此您需要找到最近的点.您可以使用 Google 地图库中的 computeDistanceBetween,也可以使用毕达哥拉斯定理,因为在这种情况下它应该可以提供足够好的准确性.

On the click event you can receive a LatLng of the coordinate that was clicked. However, since that will probably not be an exact point that is creating the polyline you need to find the closest point. You can use the computeDistanceBetween in the Google Maps library or you can use Pythagoras theorem as it should give you a good enough accuracy in this case.

您可以在此处找到有关 computeDistanceBetween 的更多信息:https://developers.google.com/maps/documentation/javascript/reference#球形

You can find more information on computeDistanceBetween here: https://developers.google.com/maps/documentation/javascript/reference#spherical

这是一个代码示例,您可以如何使用 computeDistanceBetween 来实现它.

Here is a code example how you could do it with the computeDistanceBetween.

google.maps.event.addListener(routePath, 'click', function(h) {
     var latlng=h.latLng;
     alert(routePath);
     var needle = {
         minDistance: 9999999999, //silly high
         index: -1,
         latlng: null
     };
     routePath.getPath().forEach(function(routePoint, index){
         var dist = google.maps.geometry.spherical.computeDistanceBetween(latlng, routePoint);
         if (dist < needle.minDistance){
            needle.minDistance = dist;
            needle.index = index;
            needle.latlng = routePoint;
         }
     });
     // The closest point in the polyline
     alert("Closest index: " + needle.index);

     // The clicked point on the polyline
     alert(latlng);

 });

这篇关于谷歌地图折线:点击折线部分并返回 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆