Thứ Sáu, 4 tháng 3, 2016

Java code for WGS84 to Google map position and back

java 

static void fromWebMercatorToGeographic(double mercatorX_lon, double mercatorY_lat
    ) {
        if (Math.abs(mercatorX_lon) < 180 && Math.abs(mercatorY_lat) < 90) {
            return;
        }

        if ((Math.abs(mercatorX_lon) > 20037508.3427892) || (Math.abs(mercatorY_lat) > 20037508.3427892)) {
            return;
        }

        double x = mercatorX_lon;
        double y = mercatorY_lat;
        double num3 = x / 6378137.0;
        double num4 = num3 * 57.295779513082323;
        double num5 = Math.floor((double) ((num4 + 180.0) / 360.0));
        double num6 = num4 - (num5 * 360.0);
        double num7 = 1.5707963267948966 - (2.0 * Math.atan(Math.exp((-1.0 * y) / 6378137.0)));
        mercatorX_lon = num6;
        mercatorY_lat = num7 * 57.295779513082323;
        System.out.println("mercatorY_lat=" + mercatorY_lat);
        System.out.println("mercatorX_lon=" + mercatorX_lon);
    }

I ported this to PHP - here's the code, if anyone would need it:
To mercator:
$lon = ($lon * 20037508.34) / 180;
$lat = log(tan((90 + $lat) * M_PI / 360)) / (M_PI / 180);
$lat = $lat * 20037508.34 / 180;
From mercator:
$lon = ($lon / 20037508.34) * 180;
$lat = ($lat / 20037508.34) * 180;
$lat = 180/M_PI * (2 * atan(exp($lat * M_PI / 180)) - M_PI / 2);

Here are the functions in JavaSCript ... As extracted from OpenLayers
function toMercator (lon, lat) {
  var x = lon * 20037508.34 / 180;
  var y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
  y = y * 20037508.34 / 180;

  return [x, y];
  }

function inverseMercator (x, y) {
  var lon = (x / 20037508.34) * 180;
  var lat = (y / 20037508.34) * 180;

  lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

  return [lon, lat];
  }
Fairly straightforward to convert to Java
http://stackoverflow.com/questions/7661/java-code-for-wgs84-to-google-map-position-and-back

private void FromWebMercatorToGeographic(ref double mercatorX_lon, ref double mercatorY_lat)
{
    if (Math.Abs(mercatorX_lon) < 180 && Math.Abs(mercatorY_lat) < 90)
        return;

    if ((Math.Abs(mercatorX_lon) > 20037508.3427892) || (Math.Abs(mercatorY_lat) > 20037508.3427892))
        return;

    double x = mercatorX_lon;
    double y = mercatorY_lat;
    double num3 = x / 6378137.0;
    double num4 = num3 * 57.295779513082323;
    double num5 = Math.Floor((double)((num4 + 180.0) / 360.0));
    double num6 = num4 - (num5 * 360.0);
    double num7 = 1.5707963267948966 - (2.0 * Math.Atan(Math.Exp((-1.0 * y) / 6378137.0)));
    mercatorX_lon = num6;
    mercatorY_lat = num7 * 57.295779513082323;
}
http://stackoverflow.com/questions/11957538/converting-geographic-wgs-84-to-web-mercator-102100

Không có nhận xét nào:

Đăng nhận xét