Skip to content

Instantly share code, notes, and snippets.

@korya
Created March 8, 2017 16:01
Show Gist options
  • Save korya/ed5b859f93347c12593f0e1158860d67 to your computer and use it in GitHub Desktop.
Save korya/ed5b859f93347c12593f0e1158860d67 to your computer and use it in GitHub Desktop.
Mercator Projection for Google Maps JS SDK
// Base tile size used in Google Javascript SDK
const GOOGLE_BASE_TILE_SIZE = 256;
// MercatorProjection implements the Projection interface defined in Google Maps
// Javascript SDK.
//
// Google Maps Javascript SDK docs:
// https://developers.google.com/maps/documentation/javascript/maptypes#WorldCoordinates
//
// For more details about the convertions see
// http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
class MercatorProjection {
constructor(googleMaps) {
this.googleMaps = googleMaps;
}
fromLatLngToPoint(coord) {
let siny = Math.sin(coord.lat() * Math.PI / 180);
// Truncating to 0.9999 effectively limits latitude to 89.189. This is
// about a third of a tile past the edge of the world tile.
siny = Math.min(Math.max(siny, -0.9999), 0.9999);
return new this.googleMaps.Point(
GOOGLE_BASE_TILE_SIZE * (0.5 + coord.lng() / 360),
GOOGLE_BASE_TILE_SIZE * (0.5 - Math.log((1 + siny) / (1 - siny)) / (4 * Math.PI)),
);
}
fromPointToLatLng(point) {
let n = Math.PI * (1 - 2 * point.y / GOOGLE_BASE_TILE_SIZE);
return new this.googleMaps.LatLng(
Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))) * (180 / Math.PI),
point.x / GOOGLE_BASE_TILE_SIZE * 360.0 - 180.0,
);
}
}
@MorrisseySoftware
Copy link

Thanks for this code. However can you explain when y = 0, lat = 85.1.

@MorrisseySoftware
Copy link

Sorry, I found out why. Please ignore my question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment