# Longitude/Latitude conversion

How can I convert longitude/latitude coordinates to x/y tile coordinates and back?

Another question relating to this is how they from informationfreeway.org can calculate and display the current mouse position in world coordinates.

Hope somebody can help me. I already triying a couple of days getting behind this.

There’s an example in the JOSM code: http://josm.eigenheimstrasse.de/browser/src/org/openstreetmap/josm/data/projection/Projection.java

A Google search offered some more hints, but the above JAVA code should point you in the right direction…

I’ve already found the code in Mercator.java, but this is not what I was looking for. I’m looking for an example of how to convert lon/lat to x/y-tile coordinates and back.

Well, I’m not into this projection stuff, but maybe the info in this mailing list thread will be of any help: http://lists.openstreetmap.org/pipermail/dev/2007-August/006557.html

this is a routine i’m using (in vb.net)

Private Function CalcTileXY(ByVal lat As Single, ByVal lon As Single, ByVal zoom As Long) As Point

``````    Dim xf As Single = (lon + 180) / 360 * 2 ^ zoom
Dim yf As Single = (1 - Math.Log(Math.Tan(lat * Math.PI / 180) + 1 / Math.Cos(lat * Math.PI / 180)) / Math.PI) / 2 * 2 ^ zoom
CalcTileXY.X = CLng(Math.Floor(xf))
CalcTileXY.Y = CLng(Math.Floor(yf))

End Function
``````

i’m right now searching for the inverse calculation so X,Y to lat,lon

Hey Rubke,

I am using the following methods (implemented in C++ with Qt) they work fine.
(I know, they are not implemented performantly ;))

``````QPoint coordinateToDisplay(Coordinate& coordinate, int zoom)
{
double numberOfTiles = pow(2, zoom);
// LonToX
double x = (coordinate.getLongitude()+180) * (numberOfTiles*tilesize)/360.;
// LatToY
double y = (projection /PI);
y = 1-y;
y = y /2  * (numberOfTiles*tilesize);
QPoint point = QPoint(int(x), int(y));
return point;
}

Coordinate displayToCoordinate(const QPoint& point, int zoom)
{
// longitude
double longitude = (point.x()*(360/(pow(2,zoom)*256)))-180;
// latitude
double latitude = point.y()*(2/(pow(2,zoom)*256));
latitude = 1-latitude;
latitude = latitude*PI;