I would like to query for all possible streetnames within a radius of 500 meters of a given point.
Multiple posts are reffering to the google store locator example using the Haversine formula or some version of it.
But I also came across some posts that have a much more simplified solution.
They just treat the points as x,y coordinates by adding to the lat and long variables as seen below.
I was wandering if this would be the fastest way to query mysql without getting really complicated and still get a good result. I don't have a lot of data yet, so I want to know if I am on the right track.
Are there any disadvantages or inaccuracy's by using this method?
What I don't get is how this can be a radius like range, it looks more like a one directional
query?
Distance = 0.1; // Range in degrees (0.1 degrees is close to 11km)
LatN = lat + Distance;
LatS = lat - Distance;
LonE = lon + Distance;
LonW = lon - Distance;
...Query DB with something like the following:
SELECT *
FROM table_name
WHERE
(store_lat BETWEEN LatN AND LatS) AND
(store_lon BETWEEN LonE AND LonW)
You might want to ask this question on the GIS site. I've used this answer myself for similar problems. I can see how your proposed solution might be faster, but note your four points are describing a square not a circle so it would not be considered a "radius".
You could use ElasticSearch for that, MySQL will be always slower than ES.
Related
I have a SQL database set of places to which I am assigned coordinates (lat, long). I would like to ask those points that lie within a radius of 5km from my point inside. I wonder how to construct a query in a way that does not collect unnecessary records?
Since you are talking about small distances of about 5 km and we are probably not in the direct vicinity of the north or south pole we can work with an approximated grid system of longitude and latitude values. Each degree in latidude is equivalent to a distance of km_per_lat=6371km*2*pi/360degrees = 111.195km. The distance between two longitudinal lines that are 1 degree apart depends on the actual latitude:
km_per_long=km_per_lat * cos(lat)
For areas here in North Germany (51 degrees north) this value would be around 69.98km.
So, assuming we are interested in small distances around lat0 and long0 we can safely assume that the translation factors for longitudinal and latitudinal angles will stay the same and we can simply apply the formula
SELECT 111.195*sqrt(power(lat-#lat0,2)
+power(cos(pi()/180*#lat0)*(long-#long0),2)) dist_in_km FROM tbl
Since you want to use the formula in the WHERE clause of your select you could use the following:
SELECT * FROM tbl
WHERE 111.195*sqrt(power(lat-#lat0,2)
+power(cos(pi()/180*#lat0)*(long-#long0),2)) < 5
The select statement will work for latitude and longitude values given in degree (in a decimal notation). Because of that we have to convert the value inside the cos() function to radians by multiplying it with pi()/180.
If you have to work with larger distances (>500km) then it is probably better to apply the appropriate distance formula used in navigation like
cos(delta)=cos(lat0)*cos(lat)*cos(long-long0) + sin(lat0)*sin(lat)
After calculating the actual angle delta by applying acos() you simply multiply that value by the earth's radius R = 6371km = 180/pi()*111.195km and you have your desired distance (see here: Wiki: great circle distance)
Update (reply to comment):
Not sure what you intend to do. If there is only one reference position you want to compare against then you can of course precompile your distance calculation a bit like
SELECT #lat0:=51,#long0:=-9; -- assuming a base position of: 51°N 9°E
SELECT #rad:=PI()/180,#fx:=#rad*6371,#fy:=#fx*cos(#rad*#lat0);
Your distance calculation will then simplify to just
SELECT #dist:=sqrt(power(#fx*(lat-#lat0),2)+power(#fy*(long-#long0),2))
with current positions in lat and long (no more cosine functions necessary). It is up to you whether you want to store all incoming positions in the database first or whether you want to do the calculations somewhere outside in Spring, Java or whatever language you are using. The equations are there and easy to use.
I would go with Euklid. dist=sqrt(power(x1-x2,2)+power(y1-y2,2)) . It works everywhere. Maybe you have to add a conversion to the x/y-coordinates, if degrees can't be translated in km that easy.
Than you can go and select everything you like WHERE x IS BETWEEN (x-5) AND (x+5) AND y IS BETWEEN (y-5) AND (y+5) . Now you can check the results with Euklid.
With an optimisation of the result order, you can get better results at first. Maybe there's a way to take Euklid to SQL, too.
Normally to find polygons that compasses a certain GPS point you can use a query like:
SELECT * FROM `polygons` WHERE ST_CONTAINS(`polygon`, POINT(-33.874087, 151.207865)));
However how you go with this if you would want to give the GPS point a certain margin in degrees? The only way i can currently think of is creating a MySQL function that does a loop that goes through every lat/long combination till it hits the margin and finally returns the polygons that it found. I'm however hoping there's a more efficient way to do this. I'm happy to do this in MySQL or PostgreSQL. Example input for finding compassing polygons:
latitude = 33.8275
longitude = 151.2695
latitude_span = 0.0216
longitude_span =0.0437
You can create a Buffer around the point to represent a circle, and check if it intersect the polygon. It appears to exist in both psql and mysql, but I can't find any documentation for mysql.
select polygon
from polygons
where ST_Intersects(polygon, ST_Buffer(ST_GeomFromText('POINT(100 90)'), degrees));
In my project I have to find [latitude, longitude] coordinate(s) from one point in distance of 500 meters (this could be any random coordinate or an array of coordinates around my point). How can I do this?
Note: I need this in order to find multiple paths between points different from shortest one which is returned us via Google Maps Directions Api..So using my method I will define the center of the road from A to B and then find some coordinates below and above that center position and use this as another waypoint to go from A to B - I guess this might help me to find multiple paths...
Any suggestions from GIS professionals?
EDIT: UTM conversion is the most preferable one for such calculations, and I've created UTM Java class if anyone needs..
If I understand your question right you have a known point in Lat/Long and you need calculate the Lat/Long of another point or points 500m away from your starting point.
If this is what you are doing, you have several options most of which involve specialist GIS APIs. However, I'm guesing you're a programmer/mathematician rather than a Geographer so, you may prefer to opt for using the Haversine formula. You can find a discussion on this topic here plus the formula.
One caveat is that the distamce you are working with (500m is quite small) and the Earth is far from being a perfect sphere or even a slightly flattened spheroid. It is locally "lumpy" and that can put your calculation out. If you need more accuracy you will have to account for these imperfections by using an appropriate local Datum (model of the Earth - there are many e.g. see EPSG list) and to do that you will probably need to start using the GIS libraries as the maths gets very detailed otherwise.
This is the code used by google map (SphericalUtil.java)
// from SphericalUtil.java
// compile 'com.google.maps.android:android-maps-utils:0.4.4'
public static LatLng computeOffset(LatLng from, double distance, double heading) {
distance /= 6371009.0D; //earth_radius = 6371009 # in meters
heading = Math.toRadians(heading);
double fromLat = Math.toRadians(from.latitude);
double fromLng = Math.toRadians(from.longitude);
double cosDistance = Math.cos(distance);
double sinDistance = Math.sin(distance);
double sinFromLat = Math.sin(fromLat);
double cosFromLat = Math.cos(fromLat);
double sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * Math.cos(heading);
double dLng = Math.atan2(sinDistance * cosFromLat * Math.sin(heading), cosDistance - sinFromLat * sinLat);
return new LatLng(Math.toDegrees(Math.asin(sinLat)), Math.toDegrees(fromLng + dLng));
}
to use it, you just have to enter the centerLatLng, the distance in meters, and the heading in degrees from centerLatLng.
you can change the formula to the language of your preference.
I'm working on a MYSQL/PHP system where I have the following:
-- a set of latitude, longitude in the form of (lat,lng) stored as text format : (lat1,lng1)#(lat2,lng2)#(lat3,lng3) etc. which is basically a polygon drawn over a googlemap instance stored in the database.
-- a table which stores in a field - a point's coordinates P(plat,plng) which is basically a point where a device is stationed
I need to figure out how many polygons from the first table are within a distance of X kilometers from the point P essentially using MYSQL.
I have come across quite a few Google Map libraries regarding this already, but I intend to resolve this by the quickest method possible - which I assume is via a MYSQL query.
Can anyone please please shed some light regarding this?
I've so far consulted a few examples on geospatial querying - and come up with this :
SELECT user_id, latitude, longitude,
GeomFromText( "POINT(CONCAT_WS(' ',latitude,longitude))" ) AS point,
Contains( GeomFromText( 'POLYGON(-26.167918065075458 28.10680389404297,
- 26.187020810321858 28.091354370117188, -26.199805575765794 28.125,-26.181937320958628 28.150405883789062, -26.160676690299308 28.13220977783203, -26.167918065075458 28.10680389404297)' ) ,
GEOMFromText( "POINT(CONCAT_WS(' ',latitude,longitude))" ) )
FROM user_location
But the problem is it shows a record with lat: -26.136230, long: 28.338850 as well which is way off the polygon's boundaries. Can anyone please guide?
I'm not sure if you want to calculate the distance to the nearest corner of the polygon, boundary of the polygon or some notional central point of it. Either way I think the mathmetical solution to this is to use Pythagoras' theorem to work out the proximity of points.
If you have lat1,lng1 and lat2,lng2 expressed in metres I believe that the distance between them is:
SQRT(POW(ABS(lat1 - lat2),2) + POW(ABS(lng1 - lng2),2))
Using an algorithm similar to this you need to decide whether you want to compare your known lat/lng to a single central point of the polygon or to the points of its corners (three times the work!).
MySQL does have a geospatial extension which could be worth looking at. Unfortunately I don't have experience of it.
Okay, did this - and it works - might help someone:
SELECT user_id,latitude,longitude,
Contains(
PolyFromText( 'POLYGON((-26.167918065075458 28.10680389404297, -26.187020810321858 28.091354370117188, -26.199805575765794 28.125,-26.181937320958628 28.150405883789062, -26.160676690299308 28.13220977783203, -26.167918065075458 28.10680389404297))' ),
PointFromText(concat("POINT(",latitude," ",longitude,")"))
) as contains
FROM user_location
=====
Although I agree on expert's views that PostGIS could be a better option.
Tech used: MySQL 5.1 and PHP 5.3
I am just designing a new database for a site I am writing. I am looking at the best way of now storing Lat and Lng values.
In the past I have been using DECIMAL and using a PHP/MySQL select in the form:
SQRT(POW(69.1 * (fld_lat - ( $lat )), 2) + POW(69.1 * (($lon) - fld_lon) * COS(fld_lat / 57.3 ), 2 )) AS distance
to find nearest matching places.
Starting to read up more on new technologies I am wondering if I should use Spatial Extensions. http://dev.mysql.com/doc/refman/5.1/en/geometry-property-functions.html
Information is quite thin on the ground though and had a question on how to store the data. Instead of using DECIMAL, would I now use POINT as a Datatype?
Also, once stored as a POINT is it easy just to get the Lat Lng values from it in case I want to plot it on a map or should I additionally store the lat lngs as DECIMALS again as well?
I know I should prob use PostGIS as most posts on here say I just don't want to learn a new DB though!
Follow up
I have been playing with the new POINT type. I have been able to add Lat Lng values using the following:
INSERT INTO spatialTable (placeName, geoPoint) VALUES( "London School of Economics", GeomFromText( 'POINT(51.514 -0.1167)' ));
I can then get the Lat and Lng values back from the Db using:
SELECT X(geoPoint), Y(geoPoint) FROM spatialTable;
This all looks good, however the calculation for distance is the bit I need to solve. Apparently MySQL has a place-holder for a distance function but won't be released for a while. In a few posts I have found I need to do something like the below, however I think my code is slightly wrong:
SELECT
placeName,
ROUND(GLength(
LineStringFromWKB(
LineString(
geoPoint,
GeomFromText('POINT(52.5177, -0.0968)')
)
)
))
AS distance
FROM spatialTable
ORDER BY distance ASC;
In this example geoPoint is a POINT entered into the DB using the INSERT above.
GeomFromText('POINT(52.5177, -0.0968)' is a Lat Lng value I want to calculate a distance from.
More Follow-up
Rather stupidly I had just put in the ROUND part of the SQL without really thinking. Taking this out gives me:
SELECT
placeName,
(GLength(
LineStringFromWKB(
LineString(
geoPoint,
GeomFromText('POINT(51.5177 -0.0968)')
)
)
))
AS distance
FROM spatialTable
ORDER BY distance ASC
Which seems to give me the correct distances I need.
I suppose the only thing currently that needs answering is any thoughts on whether I am just making life difficult for myself by using Spatial now or future-proofing myself...
I think you should always use the highest level abstraction easily available. If your data is geospatial, then use geospatial objects.
But be careful. Mysql is the worst geospatial database there is. Its OK for points but all its polygon functions are completely broken - they change the polygon to its bounding rectangle and then do the answer on that.
The worst example that hit me is that if you have a polygon representing Japan and you ask what places are in Japan, Vladivostok gets into the list!
Oracle and PostGIS don't have this problem. I expect MSSQL doesn't and any Java database using JTS as its engine doesn't. Geospatial Good. MySQL Geospatial Bad.
Just read here How do you use MySQL spatial queries to find all records in X radius? that its fixed in 5.6.1.
Hoorah!
Mysql GIS yagni:
If you have no experience with GIS, learning spatial extensions is practically like learning a new database, plus a little math, and a lot of acronyms. Maps, projections, srids, formats... Do you have to learn all that to calculate distances between points given a certain lat/long: probably not, will you be integrating 3rd party GIS data or working with anything more complex than points, what coordinate system will you be using?
Going back to yagni: do things as simple as posible, in this case implement your code in php or with simple SQL. Once you reach a barrier and decide you need spatial, read up on GIS system, coordinate systems, projects, and conventions.
By then, you will probably want PostGIS.
It's a good thing, because then you get to use spatial indexes on your queries. Limit to a bounding box, for example, to limit how many rows to compare against.
If you can affor placing some extra code into your backend, use Geohash.
It encodes a coordinate into a string in a way that prefixes denote a broader area. The longer your string is, the more precision you have.
And it has bindings for many languages.
http://en.wikipedia.org/wiki/Geohash
https://www.elastic.co/guide/en/elasticsearch/guide/current/geohashes.html