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

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

问题描述

当我点击地图时,哪种方法可以找到最近的标记或标记?是否有一些函数可以帮助我做到这一点?



它是google map api v3。 解决方案

首先,您必须添加eventlistener

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

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

<$ p
函数find_closest_marker(event){
var lat = event.latLng.lat(); $ p $ {code>函数rad(x){return x * Math.PI / 180;}
函数。
var lng = event.latLng.lng();
var R = 6371; //以公里为单位的地球半径
var距离= [];
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);数学公式(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;
距离[i] = d;
if(nearest == == || d< distance [nearest]){
nearest = i;
}
}

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

这会追踪最近的标记并提醒其标题。



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

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?

it's google map api v3.

解决方案

First you have to add the eventlistener

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

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天全站免登陆