繁体   English   中英

如何使用javascript显示离我所在地点最近的纬度和经度?

[英]How to display the nearest latitude and longitude to my location using javascript?

我是堆栈溢出的新手,我想知道是否有人可以帮助我使用javascript并获得最近的纬度和经度到我当前的位置。

我有一个存储纬度和经度坐标的API,我已经将它们保存在javascript变量中,并且还将我当前的位置保存在变量中。

我需要以某种方式对列表中的纬度和经度坐标进行排序,以显示距离我当前位置最近的坐标。

这有意义吗?

您可能想要包含Geolib库。

一个示例演示了getDistance函数。 如果将它与mapsort结合起来,您可以在几行中得到您想要的内容:

var current = {lat: 10, lng: 20}
var coords = [{lat: 5, lng: 5}, {lat: 10.2, lng: 19.6}, {lat: 60, lng: 10}];

var distFromCurrent = function(coord) {
    return {coord: coord, dist: geolib.getDistance(current, coord)};
}

var closest = coords.map(distFromCurrent).sort(function(a,b)  { return a.dist - b.dist })[0];

console.log("Closest: " + closest.coord.lat + ", " + closest.coord.lng);

Javascript函数来计算距离

$nearest=1; //Limit within 1 KM.

$("#jobnews").html("<h2>Results:</h2>"); 
$.each(info.companies.company, function(index, job)
{ 
    var lat = list.location.lat; 
    var lng = list.location.lng; 
    var nam = current.location.lat; 
    var cou = current.location.lng; 
    //In below line we will get the distance between current and given coordinates.
    var d=distance(nam, cou, lat, lng, "K");
    //Check the d is within 1 KM, If so then add it to map.
    if(nearest>d)
    {
        var map = "</p><img src='maps.google.com/maps/api/staticmap?center="; + lat + "," +lng +"&zoom=17&size=400x300&key="+key+"&maptype=roadmap&visual_refresh=true&markers=‌​color:red|"+lat+","+lng+"&sensor=true'width='300' height='280'alt='Map of your location.'/>"; 
        var nearestList = "<div><h3>DISPLAY INFO: "+lis.name+link+nam+lat+lng+cou+map+"</div>"; 
    }
}  

function distance(lat1, lon1, lat2, lon2, unit) {
    var radlat1 = Math.PI * lat1/180
    var radlat2 = Math.PI * lat2/180
    var radlon1 = Math.PI * lon1/180
    var radlon2 = Math.PI * lon2/180
    var theta = lon1-lon2
    var radtheta = Math.PI * theta/180
    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    dist = Math.acos(dist)
    dist = dist * 180/Math.PI
    dist = dist * 60 * 1.1515
    if (unit=="K") { dist = dist * 1.609344 }
    if (unit=="N") { dist = dist * 0.8684 }
    return dist
}        

通过功能:

lat1,lon1 =点1的纬度和经度(十进制度数)
lat2,lon2 =第2点的纬度和经度(十进制度数)
unit =您希望获得结果的单位
其中:'M'是法定里程
'K'是公里(默认)
'N'是海里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM