从已知位置查找最近列出的(阵列?)城市 [英] Finding nearest listed (array?) city from known location

查看:117
本文介绍了从已知位置查找最近列出的(阵列?)城市的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将HTML5地理位置功能整合到网站中的方法。我遇到的问题是在选定的列表中找到最近的城市/城镇。该网站只支持/销售在一定数量的城镇和城市,因此浏览器找到他们的位置并选择最近的城镇或城市。听起来很简单,但它是'找到最接近的',我可以让我的头。

我发现一个线程,帮助我通过获取来自浏览器的long / lat并将其转换为城镇名称,但这无助于找到最接近的列表:

是否有任何API(最好在Google中)能够找到最近的列出位置?我已经看过了,并且找不到任何类型的东西。

您可以使用< a href =http://rosettacode.org/wiki/Haversine_formula =nofollow> Haversine 公式。以下函数用于计算地理坐标和阵列之间的距离。

 函数deg2rad(度){
弧度=度*(Math.PI / 180);
返回弧度;
}

函数Haversine(lat1,lon1,lat2,lon2){
deltaLat = lat2 - lat1;
deltaLon = lon2 - lon1;
earthRadius = 3959; //英里数6371米。
alpha = deltaLat / 2;
beta = deltaLon / 2;数学公式(deg2rad(alpha))+ Math.scos(deg2rad(lat1))* Math.cos(deg2rad(lat2))* Math.sin(deg2rad (beta))* Math.sin(deg2rad(beta));
c = 2 * Math.atan2(Math.sqrt(a),Math.sqrt(1-a));
distance = earthRadius * c;
return distance.toFixed(2);
}


I'm looking to integrate the HTML5 geolocation functionality into a website. The issue I have is getting the nearest city/town in a chosen list. The site is only supported/marketed in a certain number of towns and cites so the idea is that the browser finds their location and chooses their nearest town or city. Sounds simple enough but it's the 'finding the nearest' that I can get my head around.

I've found a thread that has helped me through the process of getting the long/lat from the browser and turning it into their Town/City name but this doesn't help finding the nearest listed one: Reverse Geocoding With Google Map API And PHP To Get Nearest Location Using Lat,Long coordinates

Are there any APIs (preferably in Google) that will find the nearest listed location? I've had a look and can't find any of the sort.

解决方案

You can find the nearest city using the Haversine formula. The following functions are used to calculate the distance between the geolocated coordinates and the those of your array

function deg2rad(degrees){
radians = degrees * (Math.PI/180);
return radians;
}

function Haversine(lat1,lon1,lat2,lon2) {
  deltaLat = lat2 - lat1 ;
  deltaLon = lon2 - lon1 ;
  earthRadius = 3959; // in miles 6371 in meters.
  alpha    = deltaLat/2;
  beta     = deltaLon/2;
  a        = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta)) ;
  c        = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  distance =  earthRadius * c;
  return distance.toFixed(2);
}

这篇关于从已知位置查找最近列出的(阵列?)城市的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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