I have working on a web page using OpenLayers which among others shows aΒ
OpenStreetMapΒ layer.
The issue is I need to move the mouse over the map and print on a label the tileΒ nameΒ
in the form ofΒ z/x/y, for example,Β 5/15/10.
The approach to done this is:
- register a listener to the OpenLayersΒ mapΒ instance andΒ then, for every mouse event triggered,
- get the lonlat and translate it from current map projection to theΒ EPSG:4326 (WGS84).
map.events.register("mousemove", this, function (evt) {
var lonlat = new OpenLayers.LonLat(0, 0);
if (evt) {
lonlat = map.getLonLatFromPixel(evt.xy);
lonlat.transform(
this.map.getProjectionObject(),
newOpenLayers.Projection("EPSG:4326")
);
}
tileX = long2tile(lonlat.lon, map.getZoom());
tileY = latg2tile(lonlat.lat, map.getZoom());
tileZ = map.getZoom();
// Print the tilez, tilex and tiley values
});
To compute the tile X,Y grid coordinate from latlon you can use next functions (obtained fromΒ OpenStreetMapsΒ site):
// Functions to compute tiles from lat/lon
function long2tile(lon, zoom) {
return Math.floor(((lon + 180) / 360) * Math.pow(2, zoom));
}
function lat2tile(lat, zoom) {
return Math.floor(
((1 -
Math.log(
Math.tan((lat * Math.PI) / 180) + 1 / Math.cos((lat * Math.PI) / 180)
) /
Math.PI) /
2) *
Math.pow(2, zoom)
);
}