Google Maps Api v3 - 找到最近的标记 [英] Google Maps Api v3 - find nearest markers

查看:27
本文介绍了Google Maps Api v3 - 找到最近的标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击地图时,哪个是找到最近标记或标记的最佳方式?api中有一些功能可以帮助我做到这一点吗?

When i click on map, which will be best way to find nearest marker or markers? is there some functions in api that will help me to do that?

这是谷歌地图 api v3.

it's google map api v3.

推荐答案

首先要添加事件监听器

google.maps.event.addListener(map, 'click', find_closest_marker);

然后创建一个循环遍历标记数组并使用haversine 公式来计算的函数每个标记与点击的距离.

Then create a function that loops through the array of markers and uses the haversine formula to calculate the distance of each marker from the click.

function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    var R = 6371; // radius of earth in km
    var distances = [];
    var closest = -1;
    for( i=0;i<map.markers.length; i++ ) {
        var mlat = map.markers[i].position.lat();
        var mlng = map.markers[i].position.lng();
        var dLat  = rad(mlat - lat);
        var dLong = rad(mlng - lng);
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    alert(map.markers[closest].title);
}

这会跟踪最近的标记并提醒其标题.

This keeps track of the closest markers and alerts its title.

我的标记作为我的地图对象上的数组

I have my markers as an array on my map object

这篇关于Google Maps Api v3 - 找到最近的标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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