Created
December 16, 2012 18:04
-
-
Save afresh1/4310416 to your computer and use it in GitHub Desktop.
Some utility methods for converting lat/long to google/bing maps coordinates. EPSG:4326 and EPSG:3856
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Converted from http://alastaira.wordpress.com/2011/01/23/the-google-maps-bing-maps-spherical-mercator-projection/ | |
# http://trac.osgeo.org/proj/wiki/man_cs2cs | |
# similar to | |
# cs2cs -f "%.10f" +init=epsg:3857 +to +init=epsg:4326 | |
# and | |
# cs2cs -f ".10f" +init=epsg:4326 +to +init=epsg:3857 | |
# http://trac.osgeo.org/proj/wiki/man_cs2cs | |
use Math::Trig; | |
# WGS84 spheroid radius | |
# http://www.spatialreference.org/ref/epsg/4326/html/ | |
my $radius = 6378137.0; | |
# Converts between that and 900913 | |
# http://www.spatialreference.org/ref/sr-org/7483/ | |
sub lon_to_google { | |
my ($lon) = @_; | |
return 0 unless $lon; | |
return deg2rad($lon) * $radius; | |
} | |
sub lat_to_google { | |
my ($lat) = @_; | |
return 0 unless $lat; | |
my $y = rad2deg log tan deg2rad( ( 90 + $lat ) / 2 ); | |
return lon_to_google($y); | |
} | |
sub ll_to_google { | |
my ( $lon, $lat ) = @_; | |
return lon_to_google($lon), lat_to_google($lat); | |
} | |
sub google_to_lon { | |
my ($x) = @_; | |
# Without the true second argument, rad2deg passes the result | |
# through deg2deg which is modulus math and not what we want. | |
return rad2deg( $x, 1 ) / $radius; | |
} | |
sub google_to_lat { | |
my ($y) = @_; | |
my $lat = google_to_lon( $y ); | |
return rad2deg( 2 * atan( exp deg2rad $lat ) - pip2 ); | |
} | |
sub google_to_ll { | |
my ( $x, $y ) = @_; | |
return google_to_lon($x), google_to_lat($y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment