简体   繁体   English

Rails比较纬度/经度

[英]Rails Comparing Latitude/Longitude

Let's say I have 1000 objects that have a latitude/longitude value. 假设我有1000个具有经度/纬度值的对象。

What I'd like to do is send up a user's latitude/longitude and return the 50 closest objects. 我想做的是发送用户的纬度/经度并返回50个最近的对象。 I know how I could do that with one value - if I had just a latitude, but location seems different with the two values so I'm not sure how I'd do that. 我知道如何使用一个值来做到这一点-如果我只有一个纬度,但是两个值的位置似乎不同,所以我不确定该怎么做。

What would be the best way to accomplish that? 做到这一点的最佳方法是什么? Feel free to point me to a tutorial or anything - I'm very new to using location in rails :). 随时为我提供教程或其他内容-我对使用rails中的位置非常陌生:)。

There isn't any detail in the original question regarding data representation, but let's suppose you have a list of lat/long values in the form, [lat, long] in a list, locations . 原始问题中没有关于数据表示的任何详细信息,但让我们假设您有一个lat / long值列表,形式为[lat, long]locations list内。 Let's suppose further you have a metric method for the distance between them, dist(lat, long) . 让我们进一步假设您有一个度量方法,用于确定它们之间的距离dist(lat, long)

Then this will collect all of the location pair combinations and their respective distances as a collection of triples, [dist, p1, p2] : 然后,这将收集所有位置对组合及其各自的距离,作为三元组[dist, p1, p2]的集合:

location.combination(2).collect { |p| [dist(p[0], p[1]), p[0], p[1]] }

You can then sort this which will order by distance, and pick off the top 50: 然后,您可以按距离对它进行排序,并挑选出前50名:

location.combination(2).collect { |p| [dist(p[0], p[1]), p[0], p[1]] }.sort.first(50)

You'd have to see if it works with 1,000 objects, as this will create 999,000 combinations initially and I don't know what the Ruby array capacity is. 您必须查看它是否可用于1,000个对象,因为这将最初创建999,000个组合,而且我不知道Ruby数组的容量是多少。

This is a classic computer science problem called the nearest neighbor problem . 这是经典的计算机科学问题,称为最邻近问题 See this wikipedia article for two popular solutions. 有关两种流行的解决方案,请参见此Wikipedia文章

The article describes the point with x, y coordinates. 本文介绍了具有x,y坐标的点。 You can just substitute longitude for x and latitude for y. 您可以仅将经度替换为x,将纬度替换为y。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM