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.

Revisions

  1. korya created this gist Mar 8, 2017.
    38 changes: 38 additions & 0 deletions Mercator Projection.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    // 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,
    );
    }
    }