1

I've created a map and added a layer using the OpenLayers library:

map = new OpenLayers.Map('map');
var gphy = new OpenLayers.Layer.Google("Google Physical", {type: G_PHYSICAL_MAP});
map.addLayer(gphy);

The map loads and I can center my map:

map.setCenter(new OpenLayers.LonLat(-114.922485, 56.400224), 4);

I've then created a box handler, but the bounds returned aren't in Longitude / Latitude format. When drawing a box around the center of my map, my bound object returns the following:

left-bottom=(278,245) right-top=(304,211)

How can I convert these values into Longitude / Latitude?

The resolution thanks to unicoletti:

map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom))

2 Answers 2

4

Assuming that those are pixel coordinates you can use:

map.getLonLatFromPixel

or one of the other pixel to lat/lon conversion functions of the map object. Check the documentation relevant to your OL version for a detailed explanation.

1

The OpenLayers.Bounds instance you're looking at has 4 properties: left, bottom, right and top. The longitude of the bottom-left corner is bounds.left, the latitude is bounds.bottom.

Note, however, that the coordinates used by OpenLayers.Bounds and OpenLayers.LonLat are not necessarily latitudes and longitudes. They depend on the projection of the base layer. For web mercator, which is the projection when you configure your Google base layer with sphericalMercator: true, the values would be completely different. To get the latitude and longitude in this case, you would use the transform method, e.g.

bounds.transform(map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
1
  • Handler.Box actually returns a Bounds geometry with pixel coordinates, not projection coordinates.
    – relet
    Commented Nov 5, 2014 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.