[OSM-talk] calculating lon/lat bounds from tilename

Frederik Ramm frederik at remote.org
Fri Jun 22 00:09:10 BST 2007


Hi,

> Everything works great.. however I need to generate a file that
> specifies the lon/lat of the top left corner and bottom right corner of
> my grid. I have no idea how to do that (I stole the calculation for
> lon/lat -> mercator tile from the osm page that contained a perl
> example.

Here's some Java code, shouldn't be too hard to convert to something else.

The "tile..." functions will return the lat/lon of the upper left corner 
of the tile, so if you need the lower right corner you'll have to 
request the upper left of tile x+1,y+1.

public class SlippyMap {
	
	public static int latToTileY(int zoom, double lat) {
		if ((zoom < 3) || (zoom > 18)) return -1;
		double l = lat / 180 * Math.PI;
		double pf = Math.log(Math.tan(l) + (1/Math.cos(l)));
		return (int) ((1<<(zoom-1)) * (Math.PI - pf) / Math.PI);
	}
	
	public static int lonToTileX(int zoom, double lon) {
		if ((zoom < 3) || (zoom > 18)) return -1;
		return (int) ((1<<(zoom-3)) * (lon + 180.0) / 45.0);
	}
	
	public static double tileYToLat(int zoom, int y) {
		if ((zoom < 3) || (zoom > 18)) return Double.MIN_VALUE;
		return Math.atan(Math.sinh(Math.PI - (Math.PI*y / (1<<(zoom-1))))) * 
180 / Math.PI;
	}
	
	public static double tileXToLon(int zoom, int x) {
		if ((zoom < 3) || (zoom > 18)) return Double.MIN_VALUE;
		return x * 45.0 / (1<<(zoom-3)) - 180.0;
	}
}

Bye
Frederik

-- 
Frederik Ramm  ##  eMail frederik at remote.org  ##  N49°00.09' E008°23.33'




More information about the talk mailing list