首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于地理位置的排序数组

基于地理位置的排序数组
EN

Stack Overflow用户
提问于 2018-04-05 00:52:15
回答 2查看 1.8K关注 0票数 0

我想根据我的位置从最近(到我的位置)到最远对城市数组/对象进行排序

我有从数据库获取的位置列表,我如何使用javascript和HTML5地理定位来解决这个问题?

我有类似这样的东西:示例:

代码语言:javascript
运行
复制
var locations= [{"name":"location1" "latitude" :"31.413165123" 
"longitude":"40.34215241"},{"name":"location2" "latitude" :"31.413775453" 
"longitude":"40.34675341"}]

我想根据离我最近的位置对这些位置进行排序

EN

Stack Overflow用户

发布于 2018-04-05 01:18:34

存储您的位置,创建一个计算两点之间距离的函数,然后使用sort方法:

代码语言:javascript
运行
复制
function dist({latitude: lat1, longitude: long1}, {latitude: lat2, longitude: long2}) {
   // I'm not very good at geography so I don't know how to calculate exactly the distance given latitudes and longitudes.
   // I hope you can figure it out
   // the function must return a number representing the distance
}
navigator.geolocation.getCurrentPosition(({coords}) => {
   coords.latitude = parseFloat(coords.latitude)
   corrds.longitude = parseFloat(coords.longitude)

   locations.sort((p1, p2) => dist(coords, {latitude: parseFloat(p1.latitude), longitude: parseFloat (p1.longitude)}) - 
    dist(coords, {latitude: parseFloat(p2.latitude), longitude: parseFloat(p2.longitude)}))
})

希望能对你有所帮助

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49656424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档