How to convert Vector Layer coordinates into Map Latitude and Longitude in Openlayers

J.R. picture J.R. · Apr 8, 2010 · Viewed 28.8k times · Source

I'm pretty confused. I have a point:

x= -12669114.702301
y= 5561132.6760608

That I got from drawing a square on a vector layer with the DrawFeature controller.

The numbers seem...erm...awfull large, but they seem to work, because if I later draw a square with all the same points, it's in the same position, so I figure they have to be right.

The problem is when I try to convert this point to latitude and longitude.

I'm using:

map.getLonLatFromPixel(pointToPixel(points[0]));

Where points[0] is a geometry Point, and the pointToPixel function takes any point and turns it into a pixel (since the getLonLatFromPixel needs a pixel). It does this by simply taking the point's x, and making it the pixels x, and so on.

The latitude and longitude I get is on the order of:

lat: -54402718463.864
lng: -18771380.353223

This is very clearly wrong. I'm left really confused. I try projecting this object, using:

.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());

But I don't really get it and am pretty sure I did it incorrectly, anyways.

My code is here: http://pastie.org/909644

I'm sort of at a loss. The coordinates seem consistent, because I can reuse them to get the same result...but they seem way larger than any of the examples I'm seeing on the openLayers website...

Answer

amercader picture amercader · Apr 9, 2010

According to your code, the projection you are using is EPSG:900913, which is the one that Google uses. The units for this projection are meters, and the values that you obtain for the point are perfectly correct:

x= -12669114.702301 (longitude)
y= 5561132.6760608 (latitude)

This values are not pixels but coordinates in the EPSG:900913 projection, and are correct (as long as they are supposed to be in Idaho, if not there is something wrong elsewhere)

To check it, you can go to http://proj4js.org/ and transform your coordinates from EPSG:900913 to WGS84 (lat/lon), which will give you:

x = -113.8085937334033 (longitude)
y = 44.615123313472 (latitude)

This are the values you are probably expecting. If you want to obtain them from the point coordinates use something like:

point.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));

This will transform the coordinates from the Google projection to WGS84 (Latitude / Longitude).