距我的位置最近的地理位置(拉特,长) [英] Geolocation closest location(lat, long) from my position

查看:135
本文介绍了距我的位置最近的地理位置(拉特,长)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to show specific information depending on where i am.

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

I have five cities with different information, and i want to show that city(information) that i'm closest to.

如何以最简单的方式使用javascript。

How to i do that the simplest way, using javascript.

例如

如果我将城市lat,long存储在数组中

If i store the cities lat, long in an array

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

并且在我目前的位置(lat,long)我想要我喜欢的城市。

And with my current location(lat, long) i want the city that i'm closet to.

推荐答案

以下是使用HTML5地理位置获取用户位置的基本代码示例。然后它调用 NearestCity()并计算从该位置到每个城市的距离(km)。我传递了使用Haversine公式,而是使用简单的Pythagoras公式和等矩形投影来调整经度线中的曲率。

Here is a basic code example using HTML5 geolocation to get the user's position. It then calls NearestCity() and calculates the distance (km) from the location to each city. I passed on using the Haversine formulae and instead used the simpler Pythagoras formulae and an equirectangular projection to adjust for the curvature in longitude lines.

// 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]);
}

这篇关于距我的位置最近的地理位置(拉特,长)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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