Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.awt.geom.Point2D;

public class Main {
    public static final int TILE_SIZE = 256;

    /**
     * @return the Y pixel offset within the tile.
     */
    public static int getOffsetY(double lat, double lng, int zoom) {
        double y = toNormalisedPixelCoords(lat, lng).getY();
        int scale = 1 << zoom;
        y *= scale * TILE_SIZE;
        int tileY = toTileY(lat, zoom);
        return (int) (y - (TILE_SIZE * tileY));
    }

    /**
     * Returns the lat/lng as an "Offset Normalized Mercator" pixel coordinate,
     * this is a coordinate that runs from 0..1 in latitude and longitude with 0,0 being
     * top left. Normalizing means that this routine can be used at any zoom level and
     * then multiplied by a power of two to get actual pixel coordinates.
     */
    public static Point2D toNormalisedPixelCoords(double lat, double lng) {
        // first convert to Mercator projection
        // first convert the lat lon to mercator coordintes.
        if (lng > 180) {
            lng -= 360;
        }

        lng /= 360;
        lng += 0.5;

        lat = 0.5 - ((Math.log(Math.tan((Math.PI / 4) + ((0.5 * Math.PI * lat) / 180))) / Math.PI) / 2.0);

        return new Point2D.Double(lng, lat);
    }

    /**
     * @return The tile index for the latitude at the given zoom
     */
    public static int toTileY(double lat, int zoom) {
        lat = 0.5 - ((Math.log(Math.tan((Math.PI / 4) + ((0.5 * Math.PI * lat) / 180))) / Math.PI) / 2.0);
        int scale = 1 << zoom;
        return (int) (lat * scale);
    }
}