Mapserver その4


概要

ライブラリーを使わないで、googlemapやleafletのワールド座標、ピクセル座標、タイル座標を求めてみた。

写真

成果物

サンプルコード

var MERCATOR_RANGE = 256;
function bound(value, opt_min, opt_max) {
    if (opt_min != null) value = Math.max(value, opt_min);
    if (opt_max != null) value = Math.min(value, opt_max);
    return value;
}
function degreesToRadians(deg) {
    return deg * (Math.PI / 180);
}
function radiansToDegrees(rad) {
    return rad / (Math.PI / 180);
}
function MercatorProjection() {
    this.pixelOrigin_ = {
        x: MERCATOR_RANGE / 2, 
        y: MERCATOR_RANGE / 2
    };
    this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
    this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
};
MercatorProjection.prototype.fromPointToLatLng = function(point) {
    var me = this;
    var origin = me.pixelOrigin_;
    var lng = (point.x - origin.x) / me.pixelsPerLonDegree_;
    var latRadians = (point.y - origin.y) / -me.pixelsPerLonRadian_;
    var lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
    return {
        lat: lat, 
        lng: lng
    };
};
MercatorProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
    var me = this;
    var point = opt_point || {
        x: 0, 
        y: 0
    };
    var origin = me.pixelOrigin_;
    point.x = origin.x + latLng.lng * me.pixelsPerLonDegree_;
    var siny = bound(Math.sin(degreesToRadians(latLng.lat)), -0.9999, 0.9999);
    point.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -me.pixelsPerLonRadian_;
    return point;
};
function test0() {
    var zoom = 11;
    var x = +document.getElementById('x').value;    
    var y = +document.getElementById('y').value;
    var projection = new MercatorProjection();
    var point = {
        x: (x * MERCATOR_RANGE) / Math.pow(2, zoom),
        y: (y * MERCATOR_RANGE) / Math.pow(2, zoom)
    }
    var latlng = projection.fromPointToLatLng(point);
    document.getElementById('koko0').innerHTML = latlng.lng + " " + latlng.lat;
}
function test1() {
    var zoom = 11;
    var lng = +document.getElementById('lng').value;    
    var lat = +document.getElementById('lat').value;
    var projection = new MercatorProjection();
    var latlng = {
        lat: lat,
        lng: lng
    };
    var worldCoordinate = projection.fromLatLngToPoint(latlng);
    var pixelCoordinate = {
        x: worldCoordinate.x * Math.pow(2, zoom), 
        y: worldCoordinate.y * Math.pow(2, zoom)
    };
    var tileCoordinate = {
        x: Math.floor(pixelCoordinate.x / MERCATOR_RANGE), 
        y: Math.floor(pixelCoordinate.y / MERCATOR_RANGE)
    };
    document.getElementById('koko1').innerHTML = tileCoordinate.x + " " + tileCoordinate.y;
}