Determine/create a geofence/bounding box on the fly - mysql

I have a MySQL table of lat/lon (think of a school campus or shopping mall).
Each location (school/mall) can have dozens of GPS positions stored in the table. All locations are captured using a mobile app and these locations can represent everything from entrances to specific rooms (conference) to easily identifiable locations such as elevators.
A user submits a request (i.e. janitor cleanup on isle 6) and I need to make sure the request (cleanup) being submitted is within the geofence established by finding the 4 points furthest away from each other for that location.
Currently we're using a Haversine search but we want to convert this to a fenced in system. What we can't do is build a separate geofence table.
I've googled around and not found anything (I'm probably not using the correct terms). How do I build that query?

At the first level of approximation, you can scan for a bounding box.
Say you have a loc table with loc_id, lat, lng columns.
And say your candidate point has the position #ptLat, #ptLng.
Compute the bounding boxes for each location. This works fine with latitude and longitude unless you're within a few degrees of the north or south pole or near 180° longitude.
SELECT loc_id, MAX(lat) north, MAX(lng) east, MIN(lat) south, MIN(lng) west
FROM loc
GROUP BY loc_id
This is fast if you have an index on (loc_id, lat, lng). It's also fast because you can avoid all the trig functions in the Great Circle calculation.
Once you have the bounding box, you can decide whether your candidate point is inside it.
Then you can do
SELECT loc_id
FROM (
SELECT loc_id, MAX(lat) north, MAX(lng) east, MIN(lat) south, MIN(lng) west
FROM loc
GROUP BY loc_id
) box
JOIN ( SELECT #ptLat ptLat, #ptLon, ptLon ) pt
ON ptLat <= north
AND ptLat >= south
AND ptLon <= east
AHD ptLon >= west
This gets you a result set with the loc_id values matching your candidate point.
If your lat,lng data is messy--if it has lots of outlier points--this won't work very well. It's sensitive to errors. For example, if a location in Iceland has lots of points right near it, but one point in Greenland miscoded, the bounding box will be absurdly large.
If it isn't accurate enough for you, you should research convex hull algorithms. But that will take you outside pure SQL, most likely.

Related

Google geocoding viewports

Does the viewports in the Google geocoding represents the boundary boxes of the location ? Iam trying to use google viewports of particular city or location to search for the latitude and longitude values that fall in those bounding values.
I have two tables called tblproperty and tblemailalerts, tblproperty has got latitude and longitude values and tblemailalerts also got viewport + latitude and longitude values . Now I want to get the sql to get the matching records with accuracy
I want to achieve similar to zoopla search
for example when user selects location as london , properties should be shown within the boundaries of london. If they select london within 1/4 mile radius i should get the properties within the london + properties with 1/4 radius
The viewport bounds parameter only biases the results. It's not a hard limit. You can read about viewport biasing in the API documentation.
However, the viewport returned by Google for a query for "London" does represent a bounding box you can use in your SQL query.
You could also use the OpenStreetMap API. The query to get a bounding box for London is:
http://nominatim.openstreetmap.org/search?q=London&format=json
In there you will find a number of bounding boxes for places called "London" around the world, but the first one is London, United Kingdom.

Is there a numeric road identifier in google maps?

I'm looking for a way to identify roads or streets on google maps.
I don't need the road name, just an identifier for a road. And I don't really care if GPS coordinate is really on the road as long as the results are consistent.
I need this in order to determine if two GPS coordinates are on the same road.
Now I know I can compare the road name between the two coordinates using geocoder but In some cases the road name is null, and I actually don't care about the name itself.
Is there any road ID that I can get using a geocoder ?
What do you mean by the 'same road'?
A road can have many different names and designations at the same time and over its length.
Consider Route 66 do you want to be considered to be on the same road if you are on the same road if your two locations are on route 66 near Los Angeles and Chicago or is it a series of different roads as wends its way through the cities en-route?
Should a road have a different id if has an arbitrary name change as it goes round a bend or crosses from one town to the next?

Preferred order of writing latitude & longitude tuples in GIS services

When dealing with GIS source code you often need to write latitude and longitude coordinate tuples.
E.g. in Google Maps links (123, 456):
http://maps.google.com/maps/ms?msid=214518704716144912556.00046d7689a99e95b721c&msa=0&ll=123,456&spn=0.007996,0.026865
Which is preferred order (and why?)
latitude, longitude
longitude, latitude
I have seen both being used in various systems and I hope to find some evidence to stick with other one.
Is there a standard practice, and if so, what is it / what are they?
EPSG:4326 specifically states that the coordinate order should be latitude, longitude. Many software packages still use longitude, latitude ordering. This situation has wreaked unimaginable havoc on project deadlines and programmer sanity.
The best guidance one can offer is to be fully aware of the expected axis order of each component in your software stack. PostGIS expects lng/lat. WFS 1.0 uses lng/lat, but WFS 1.3.0 defers to the standard and uses lat/lng. GeoTools defaults to lat/lng but can be overridden with a system property.
The GeoTools docs on the history and explanation of the problem are worth a read:
http://docs.geotools.org/latest/userguide/library/referencing/order.html
The prefered order is by convention latitude, longitude. This was presumably standardized by
the International Maritime Organization
as reported here. Google also uses this order in its Maps and Earth. I remember this order by thinking of alphabetic order of latitude, longitude.
The correct order is longitude, latitude, in virtually all professional GIS applications, as it is in conventional math (ie, f(x ,y, z)). The GeoJSON standard is fairly typical and succinct:
The order of elements must follow x, y, z order
(easting, northing, altitude for coordinates in a
projected coordinate reference system, or longitude,
latitude, altitude for coordinates in a geographic
coordinate reference system).
The same is true of the primary Open Geospatial Consortium standards (WKT and WKB, and extensions like EWKB). Likewise Google may output the order in Lat/Lon to make it more familiar to users who grew up with that custom (ie from navigation standards like IMO, rather than computational ones.) But the KML standard itself is like virtually all other GIS systems:
The KML encoding of every kml:Location and coordinate
tuple uses geodetic longitude, geodetic latitude, and
altitude (in that order).
Good rule of thumb: if you know what a tuple is and are programming, you should be using lon,lat. I would even say this applies if your end user (say a pilot or a ship captain) will prefer to view the output in lat,lon. You can switch the order in your UI if necessary, but the overwhelming majority of your data (shapefiles, geojson, etc.) will be in the normal Cartesian order.
By convention in 'real-life', when giving a position, the latitude (i.e. North/South) is always given 1st, e.g. 20°N 56°W (although, this doesn't follow normal convention if thinking about a standard Cartesian grid); similarly, all co-ordinates on Wikipedia follow this convention (e.g. see location for Southampton: http://en.wikipedia.org/wiki/Southampton). To save confusion, especially when units aren't being included, I'd always recommend that the latitude is given 1st in a tuple.
So the preferred order depends on personal preference!
Latitude came first; the equinox has been known for millenia, as the days the "sun crosses the equator"; in March crossing from S to N and Sept from N to S.The only question might have been whether the Equator should have been 0 or 90 degrees. By taking 0 deg, the angle between vertical and the midday solar zenith on the equinox is the latitude of a location, everywhere on the planet. The prime latitude, or prime parallel effectively defined itself.
Longitude could only be by agreement. Britain put up a Longitude prize. Britain needed its ships to know where they were and needed better maps. Harrison (http://www.youtube.com/watch?v=T-g27KS0yiY) produced an accurate marine chronometer; they sent mapmaking voyaging journeys eg James Cook 1770's. Britain therefore claimed the Prime Meridian by using Greenwich as 000deg for their maps. After 100 years of their use, the Prime Meridian was accepted internationally, in 1884.
In Christopher Columbus time Latitude was the only number they had. The strategy was to traverse a parallel before turning left or right for destination; watching for clouds or birds. Measuring speed in knots every hour was common but did not account for currents. Perhaps Columbus's greatest achievement was getting back home from the West Indies four times. Without that, land he discovered could not be added to the maps.
Read "Longitude" by Dava Sobel (ISBN: 9780007214228)
ISO 6709 standardizes listing the order as latitude, longitude for safety reasons. Graham's explanation above sounds correct to me as well. Someone suggested this answer isn't related to the question--it absolutely is, and explains why the order is often given as latitude, longitude.
This is how it has been listed for however long navigators have been using the system; changing that now would be confusing, and as ISO suggests, potentially dangerous. GIS softwares, like ArcMap, list them the other way around because that is the typical convention for x,y coordinate pairs. Latitude is y, longitude is x, so that's how Arc lists them.
Personally I've never seen anything but latitude followed by longitude.
And, when using + and - instead of N and S, it's always been + is N and - is S.
I have observed variation when using + and - for E and W. Generally + has been E and - has been W. However, on older applications where they were dealing overhwlemingly with W longitudes, I've seen + be W and - be E.
Hopefully you'll not have to be dealing with applications that old.
Apart from GeoJSON spec, which others have already mentioned, there are other practical cases where longitude,latitide order is recommended, even mandatory - e.g.: geospatial indexing in MongoDB. If you get the order wrong there, your queries will return wrong results, as if performed again a transposed dataset.
Longitude then Latitude (lon, lat).
When projected to Mercator longitude defines the x direction and latitude defines the y direction. Most geometry libraries strictly uses this format of (lon, lat) as it is the most intuitive way to think of geographic coordinates in a 2D plane.

Ms SQL geography.STDistance returns wrong distance

I'm trying to query any locations within a specified distance from another location. The query is not the problem, but the distance returned by geography.STDistance is.
It seems STDistance makes fairly accurate calculations on locations close to the equator, but I need this to work with locations in the nordic countries. Norway, Sweden, Finland and so on...
According to my calculations, made on locations in northern Sweden, the distance is wrong by a factor of around 2.38?!
Expected result is 1070 meters and returned distance is 2537,28850694302 meters
My query looks like this:
DECLARE #g geography = geography::STGeomFromText('POINT(65.580254 22.179428)', 4326)
SELECT name, [pos].STSrid as srdi, [pos].STDistance(#g) as d
FROM [GPSCHAT].[dbo].[USERS]
and the "other location" has coordinates (65,578541 22,202286) (stored with SRID 4326)
I'm guessing this has to do with the distance from the equator (close to the polar circle), but there has to be a way to calculate this more accurately based on the Latitude or am i wrong?
It looks like you're creating your point using 'X, Y'.
When creating a point from text, use 'Y, X' instead.
Check out this MSDN Article for some more info.
Why don't you make use of another spatial reference identifier which fits better the earth curvature around your position. SRID 4326 might not been measured as accurate as other local referential systems

Eeek! - Calculate Radius having only latitudes and longitudes

I have a MySQL database that looks as such:
Postcode int(4),
City varchar,
State varchar,
Latitude decimal(7,4),
Longitude decimal(7,4)
I want the user to enter their post code (1660 for example) and a radius of x (lets say 10) miles or kilometers. When they hit search, I want to return a list of all the cities within that radius. I have a database that contains all of the post codes, cities, latitudes, longitudes etc. of all areas within Australia.
If you could sacrifice some precisions (by selecting cities within a rectangle area 10 miles from post code 1660), then the solution can be as simple as:
Find out the latitude and longitude of post code 1660
Calculate the top left and bottom right of the rectangle area (10 miles to the left and top, 10 miles to the bottom and right)
Use the query like: select city from table where latitude between bottom_right_latitude and top_left_latitude and longitude between top_left_longitude and bottom_right_longitude
If it has to be precisely radius 10 miles (which means the area is a circle), then the solution will be very complicated, couldn't do it in a single query I afraid. You need to think about some helper columns and use the distance and bearing calculations formulas to do it.
Reference: Calculate distance, bearing and more between Latitude/Longitude points