javascript - 地理位置离我的位置最近的位置(纬度,经度)

标签 javascript jquery html geolocation

我想根据我所在的位置显示特定信息。

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

如何使用 javascript 以最简单的方式做到这一点。

例如

如果我将城市经纬度存储在一个数组中

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

根据我当前的位置(纬度、经度),我想要离我最近的城市。

最佳答案

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

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

关于javascript - 地理位置离我的位置最近的位置(纬度,经度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21279559/

相关文章:

javascript - 您可能需要适当的加载程序来处理此文件类型。当我在 create-react-app 项目中使用可选链接运算符时

javascript - 复制包含纯文本的 div 内容并选择菜单

CSS div float - 移动 div

javascript - AngularJS:如何在选择另一个跨度时取消选择一个跨度

javascript - 使用 Javascript 按另一个数组对 JSON 进行排序,其余按字母顺序排序

javascript - 我可以在javascript中使用大括号来分隔代码段吗

javascript - 禁用文本框时如何在 jquery 中禁用此上下文菜单

javascript - Chrome/Windows 7 上 JavaScript 的 Alt 键行为?

jquery - 将 html 内容加载为 json

javascript - JavaScript 输入和输出之间的一(按键)事件延迟