Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Working With Lattitude And Longitude

This post is a work in progress and is just a resource index and notes to begin with.

Working with Latitude and Longitude is not straight-forward because they are not linear units owing to the fact that the earth is not flat. This means that using native spatial operations would result in some degree of error if you were to use them to try and find the nearest point t a location, or check if a location is within a custom drawn polygon.

The Google Maps API provides us with the query we would need to send MySQL IN ORDER TO find the closest 20 locations that are within a radius of 25 miles to the coordinate (37, -122).

SELECT 
id, 
( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance 
FROM markers 
HAVING distance < 25 
ORDER BY distance 
LIMIT 0 , 20;

I imagine that such a query would be quite slow if you had lots of points in your database (need to test), so it would probably be better to perform an quicker erroneous operation first to cut down the number of possible points to evaluate.

Javascript API

Google also also provide a Javascript API which will help you if you can perform the operations on the client-side.

Also, tools such as Leaflet let you just provide the coordinates and will perform the necessary mathematical operations for you. This is what I used for my road data application which lets the user draw a polygon over the area they wish to investigate. This will result in them seeing how many casualties there were in 2014 for that area.

Latitude and Longitude Values

The valid range of latitude in degrees is -90 and +90 for the southern and northern hemisphere respectively. Longitude is in the range -180 and +180 specifying the east-west position.

The Equator has a latitude of 0°, and the Prime Meridian (which goes through Greenwich, England) has a longitude of 0°. The International Date Line (IDL) roughly follows the 180° longitude. A longitude with a positive value falls in the eastern hemisphere and negative value falls in the western hemisphere.

Resources

References

Last updated: 16th August 2018
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch