[英]How to find nearest location using latitude and longitude from a json data
[英]How to display the nearest latitude and longitude to my location using javascript?
我是堆棧溢出的新手,我想知道是否有人可以幫助我使用javascript並獲得最近的緯度和經度到我當前的位置。
我有一個存儲緯度和經度坐標的API,我已經將它們保存在javascript變量中,並且還將我當前的位置保存在變量中。
我需要以某種方式對列表中的緯度和經度坐標進行排序,以顯示距離我當前位置最近的坐標。
這有意義嗎?
您可能想要包含Geolib庫。
第一個示例演示了getDistance
函數。 如果將它與map
和sort
結合起來,您可以在幾行中得到您想要的內容:
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.