当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - find query through floating values

问题描述:

I'm trying to figure out a way to query based on two floating values. In my case these are longitude and latitude.

Currently I'm calculating shortest distance to point A, using Google Matrix API. That again returns me the longitude and latitude of the shortest distance.

Now I'd like to be able to use that to find the location in my database.

I've tried using Location.find_by(latitude: value, longitude: value) and for some reason this works sometimes, but not other times.

Even though I'm copy pasting the values from the database into it. So now I'm trying to figure out a way I can easily figure out which location it has calculated as shortest as this query seems to be inaccurate.

Any ideas on tackling this?

网友答案:

I think you should give this gem a try: https://github.com/alexreisner/geocoder

It has some really useful helpers such as:

Location.near([40.71, -100.23], 20, :units => :km)
                               # Locations within 20 kilometres of a point

Also this gem works really well with Google or other Map Api.

The thing with "find_by" it that it will search for the exact same values. So depending on your rounding, it may not be the exactly same value as the one stored in the database. So if you still want to use that, you should be really careful with the values you get from Google and the ones stored in your DB.

Also you put same value variable in your code:

Location.find_by(latitude: value, longitude: value)

But perhaps you did not do an exact copy/paste of your code? That should rather be:

lat = point_latitude
lng = point_longitude
Location.find_by(latitude: lat, longitude: lng)
网友答案:

Here you are trying to query where both latitude and longitude are same.

You should try something like:

Location.find_by(latitude: lat_value, longitude: long_value)

whereas lat_value and long_value contain the required values against which you want to query.

分享给朋友:
您可能感兴趣的文章:
随机阅读: