How to find "nearby" results? - rdbms

Assuming you have the latitude and longitude of your user, and you want to find nearby... let's say restaurants, how do you query your relational DB? For something like "restaurants within a 25 mile radius"?
Would you just query for restaurants in a square with a long and lat greater than/less than the user's loc +/- 25 miles (converted to degrees I guess), and then filter out the "corners" in whatever language your using? Or can/should you do it directly in the SQL?

Take a look at the spatial features available in oracle for instance - here is the wikipedia entry http://en.wikipedia.org/wiki/Spatial_query, and a link with examples from noaa https://www.ngdc.noaa.gov/wiki/index.php?title=Sample_Oracle_Spatial_Queries

Found a really good guide here: http://code.google.com/apis/maps/articles/phpsqlsearch.html
Much simpler than many of the other explanations...

Use a SQL implementation of the Haversine formula

Your "circle" will already be quite deformed if you are treating lat/long as a rectilinear grid any significant distance from the equator (like, say, in New York, or London, or Moscow). Trimming the corners off the "square" doesn't improve it much.

I know you specifically mentioned relational databases, but I would reco that you at least look into a system which has a native implementation of spacial querying.
Personally, I've found MongoDB to be pretty elegant: http://www.mongodb.org/display/DOCS/Geospatial+Indexing

Related

Accuracy of MongoDB Intersect Query

I read somewhere that MongoDB doesn't accurately do spatial searches, as it creates a bounding box around the objects and checks if they intersect, rather than checking whether the original shapes actually intersect. Annoyingly I can't find this webpage again.
Has anyone else had this experience?
UPDATE:
I'm trying to decide whether to use MongoDb or PostGis for a scalable web system (Java Spring-Boot back-end), which requires accurate intersection queries. So for PostGis I'd probably use ST_Overlaps, and for MongoDb $geoIntersects. I will also use the spatially near functions however their accuracy isn't so important.
Thanks :)

Best practice for unit conversion between imperial and metric

I have an app I'd like to open up to an international audience & so I need to accept different units, to keep it simple let's say miles & kilometers.
I figured I've got 3 options:
Use Meteor's transform option on my collection
Use Simple Schema's autoValue
Manually adjust the value every time I send/receive it from the DOM
Store mi/km in different fields (take advantage of that NoSQL!)
?
What is the pattern you've found most useful? Any examples would be great.
For smaller units of measure like yards and meters, I would use an integer of centimeters. It can be converted to any unit larger than itself easily and you shouldn't have any issues with floats. On a scale of miles and kilometers, I'd store integers of meters.
As far as how to transform them back and forth, I'd keep that in the view, not the model. I'm not a meteor guy so I'm not sure how that translates, but I'm saying I'd use javascript to either multiply meters by 1000 for kilometers or by 1609 for miles. There's even Javascript libraries to assist in this kind of internationalization.

Query to find distance between a point column and a point in PostGis

I am using PostGis for Location based calculations in my Application. In a Table i have a column called 'location' in geography type(Point(lon lat))...Like this number of rows present in the Table.
I want to pass a point(Point(lon lat)) and check distance between this point(i passed) and location column in all rows....and if distance is less than 5 m....it will return the name of the point.How to query this.
Assuming that your srid of your data is 4326 the query you are looking for is:
SELECT the_geom FROM mytable WHERE ST_DWithin(the_geom,ST_GeomFromEWKT("srid=4326;POINT(lon lat)"), 0.0008);
Note that the units(0.0008) in ST_DWithin are in the same units of your projection, in the 4326 case they are degrees. If your projection data is in meters, you will be able to use meters.
For a production application you should use geometry types, is faster. From a stackoverflow previous question:
Short Answer: geography is a new data type that supports long range
distances measurements. If you use geography -- you don't need to
learn much about planar coordinate systems. Geography is generally
best if all you care about is measuring distances and lengths and you
have data from all over the world. Geometry datatype is an older data
type that has many functions supporting it and enjoys great support
from third party tools. Its best if you are pretty comfortable with
spatial reference systems or you are dealing with localized data where
all your data fits in a single spatial reference system (SRID), or you
need to do a lot of spatial processing. Refer to Section 8.8, “PostGIS
Function Support Matrix” to see what is currently supported and what
is not.
Great.Thank You. It works fine in database. I have following code from PHP..it returs like, Query Failed:
$locationresult=pg_query($con,"SELECT id,name FROM gps.locationnames WHERE ST_DWithin(location,ST_GeographyFromText('POINT(lon lat)'),500)") or die ('Query Failed:'.pg_last_error($con));
What is the problem here..

What SRID should I use for my application and how?

I'm using PostgreSQL with PostGIS. All my data has already decimal lat/long attached to it (i.e. -87.34554 33.12321) but to use PostGIS I need to convert it to a certain type of SRID.
The majority of my queries are looking for data inside a certain radius.
What SRID should I use? I created already a geometry column with SRID 4269.
In this example:
link text the author is converting SRID 4269 to SRID 32661. I'm very confused about how and when to use these SRIDs. Any lite on the subject would be truly appreciated.
As long as you never intend to reproject/transform the data to another coordinate system, it doesn't technically matter what srid you use. However assuming you don't want to throw away that important metadata, and you do want to transform it, you will want to ensure your assigned srid matches the data, so postgis knows what to do when the time comes.
So why would you want to reproject from epsg:4269? The answer is because certain types of queries (such as distance) make no sense in this 'unprojected' world. Your units are in decimal degrees, and a straight measurement of x decimal degrees is a different real distance depending where in the planet you are.
In your example above, someone is using epsg:32661 as they believe it will give them better accuracy for the are they're working in. If your data is in a specific area of the globe, you can select a projection that's accurate for that area. If it spans the entire globe, you have to choose a projection that does 'ok' for your needs.
Now fortunately PostGIS has a few ways of making all this easier. For approx distances you can just use the st_distance_sphere function which, as you might guess, assumes the earth is a sphere. Or the more accurate st_distance_spheroid. Using these, you don't need to reproject and you will probably be fine for your distance queries except in edge cases. Newer versions of PostGIS also let you use geography columns
tl;dr - use st_distance_spheroid for your distance queries, store your data in geography columns, or transform it to a local projection (when storing, or on the fly, depending on your needs).
Take a look at this question: How do you know what SRID to use for a shp file?
The SRID is just a way of storing the WKT inside the database (you may have noticed that, altough you store lat/long points, the preferred storing is a long string with number and capital letters).
The SRID or EPSG can be different for the country/state/... altough there are some very common ones especially the 2 mentioned by you. If you need specific info what area uses what SRID, there is a database for handling that.
Inside your database, you have a table spatial_ref_sys that has the information on what SRID PostGIS knows about.

Calculation route length

I have a map with about 80 annotations. I would like to do 3 things.
1) From my current location, I would like to know the actual route distance to that position. Not the linear distance.
2) I want to be able to show a list of all the annotations, but for every annotation (having lon/lat) I would like to know the actual route distance from my position to that position.
3) I would like to know the closest annotation to my possition using route distance. Not linear distance.
I think the answer to all these three points will be the same. But please keep in mind that I don't want to create a route, I just want to know the distance to the annotation.
I hope someone can help me.
Best regards,
Paul Peelen
From what I understand of your post, I believe you seek the Haversine formula. Luckily for you, there are a number of Objective-C implementations, though writing your own is trivial once the formula's in front of you.
I originally deleted this because I didn't notice that you didn't want linear distance at first, but I'm bringing it back in case you decide that an approximation is good enough at that particular point of the user interaction.
I think as pointed out before, your query would be extremely heavy for google maps API if you perform exactly what you are saying. Do you need all that information at once ? Maybe first it would be good enough to query just some of the distances based on some heuristic or in the user needs.
To obtain the distances, you could use a Google Maps GDirections object... as pointed out here ( at the bottom of the page there's "Routes and Steps" section, with an advanced example.
"The GDirections object also supports multi-point directions, which can be constructed using the GDirections.loadFromWaypoints() method. This method takes an array of textual input addresses or textual lat/lon points. Each separate waypoint is computed as a separate route and returned in a separate GRoute object, each of which contains a series of GStep objects."
Using the Google Maps API in the iPhone shouldn't be too difficult, and I think your question doesn't cover that, but if you need some basic example, you could look at this question, and scroll to the answer.
Good Luck!
Calculating route distance to about 80 locations is certain to be computationally intensive on Google's part and I can't imagine that you would be able to make those requests to the Google Maps API, were it possible to do so on a mobile device, without being severely limited by either the phone connection or rate limits on the server.
Unfortunately, calculating route distance rather than geometric distance is a very expensive computation involving a lot of data about the area - data you almost certainly don't have. This means, unfortunately, that this isn't something that Core Location or MapKit can help you with.
What problem are you trying to solve, exactly? There may be other heuristics other than route distance you can use to approximate some sort of distance ranking.