Skip to content

Instantly share code, notes, and snippets.

@jezhalford
Created April 24, 2012 15:45
Show Gist options
  • Save jezhalford/2480871 to your computer and use it in GitHub Desktop.
Save jezhalford/2480871 to your computer and use it in GitHub Desktop.
Map Lat/Lon onto map pixels
/**
* Convert Latitude and Longitude to CSS top and left positions for a map image.
* Works with any map image that uses Spherical Mercator Projection (the same as Google Maps)
*
* From http://stackoverflow.com/a/7021776/86780
*/
var latLonToTopLeft = function(lat, lon) {
var imageNorthLat = 59.545457; // Latitude of the image's northern edge
var imageSouthLat = 49.431947; // Latitude of the image's southern edge
var imageWestLong = -11.140137; // Longitude of the image's western edge
var imageEastLong = 2.757568; // Longitude of the image's eastern edge
var imageLongPixels = 1250; // Width of the image in pixels
var imageLatPixels = 1600; // Height of the image in pixels
var pixelsPerLat = imageLatPixels / (imageNorthLat - imageSouthLat);
var pixelsPerLong = imageLongPixels / (imageEastLong - imageWestLong);
var x = (lon-imageWestLong) * pixelsPerLong;
var y = Math.abs(lat-imageNorthLat) * pixelsPerLat;
return {
'left' : x,
'top' : y
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment