从我的位置地理位置最近的位置(纬度,长度)

我想根据我的位置显示具体信息。

我有五个不同信息的城市,我想展示我最接近的城市(信息)。

我怎么用最简单的方法,使用javascript。

防爆。

如果我将城市lat存储在一个数组中

var cities = [ ['new york', '111111', '222222', 'blablabla'] ['boston', '111111', '222222', 'blablabla'] ['seattle', '111111', '222222', 'blablabla'] ['london', '111111', '222222', 'blablabla'] ] 

随着我目前的位置(拉特,长)我想要的城市,我是壁橱。

这是一个使用HTML5地理定位来获取用户位置的基本代码示例。 然后它调用NearestCity()并计算从该位置到每个城市的距离(km)。 我继续使用Haversine公式,而是使用更简单的Pythagoras公式和一个equirectangular投影来调整经度线的曲率。

 // Get User's Coordinate from their Browser window.onload = function() { // HTML5/W3C Geolocation if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(UserLocation); } // Default to Washington, DC else NearestCity(38.8951, -77.0367); } // Callback function for asynchronous call to HTML5 geolocation function UserLocation(position) { NearestCity(position.coords.latitude, position.coords.longitude); } // Convert Degress to Radians function Deg2Rad(deg) { return deg * Math.PI / 180; } function PythagorasEquirectangular(lat1, lon1, lat2, lon2) { lat1 = Deg2Rad(lat1); lat2 = Deg2Rad(lat2); lon1 = Deg2Rad(lon1); lon2 = Deg2Rad(lon2); var R = 6371; // km var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2); var y = (lat2 - lat1); var d = Math.sqrt(x * x + y * y) * R; return d; } var lat = 20; // user's latitude var lon = 40; // user's longitude var cities = [ ["city1", 10, 50, "blah"], ["city2", 40, 60, "blah"], ["city3", 25, 10, "blah"], ["city4", 5, 80, "blah"] ]; function NearestCity(latitude, longitude) { var mindif = 99999; var closest; for (index = 0; index < cities.length; ++index) { var dif = PythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]); if (dif < mindif) { closest = index; mindif = dif; } } // echo the nearest city alert(cities[closest]); } 

使用HTML5,您可以提取用户的位置,然后使用Haversine函数比较此示例( 下面的函数取自此处 ):

 function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) { var R = 6371; // Radius of the earth in km var dLat = deg2rad(lat2-lat1); // deg2rad below var dLon = deg2rad(lon2-lon1); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; // Distance in km return d; } function deg2rad(deg) { return deg * (Math.PI/180) } 

您可以按纬度计算您的位置和城市位置的距离。 并找到最短和绘制。 要计算,您可以在http://www.movable-type.co.uk/scripts/latlong.html上阅读更多内容