I'm using Leaflet 1.0.0rc3 and need to use an absolute pixel value to modify something on my map. Thus, I want to know where the user clicks in pixels, and then transform this back to LatLng
coordinates. I tried using map.unproject()
, which seems like the correct method (unproject() Leaflet documentation). But the LatLng values that come out of that method are very different from the output of e.latlng
. (E.g., input LatLng (52, -1.7)
and output LatLng (84.9, -177)
). So I must be doing something wrong.
Question: What's the proper way to project points from layer (x,y) space to LatLng space?
Here's a code snippet (fiddle: https://jsfiddle.net/ehLr8ehk/)
// capture clicks with the map
map.on('click', function(e) {
doStuff(e);
});
function doStuff(e) {
console.log(e.latlng);
// coordinates in tile space
var x = e.layerPoint.x;
var y = e.layerPoint.y;
console.log([x, y]);
// calculate point in xy space
var pointXY = L.point(x, y);
console.log("Point in x,y space: " + pointXY);
// convert to lat/lng space
var pointlatlng = map.unproject(pointXY);
// why doesn't this match e.latlng?
console.log("Point in lat,lng space: " + pointlatlng);
}
setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng latln) { // TODO Auto-generated method stub String s=latln. toString(); Log. w("dsfdsf",""+s); } }); It provides be the latitude and longitude coordinates in the format lat/lng: (xx.
Simple. CRS stands for coordinate reference system, a term used by geographers to explain what the coordinates mean in a coordinate vector.
You are just using a wrong method. To convert layer points to LatLng
in Leaflet you need to use map.layerPointToLatLng(point)
method.
So your code should look like this:
// map can capture clicks...
map.on('click', function(e) {
doStuff(e);
});
function doStuff(e) {
console.log(e.latlng);
// coordinates in tile space
var x = e.layerPoint.x;
var y = e.layerPoint.y;
console.log([x, y]);
// calculate point in xy space
var pointXY = L.point(x, y);
console.log("Point in x,y space: " + pointXY);
// convert to lat/lng space
var pointlatlng = map.layerPointToLatLng(pointXY);
// why doesn't this match e.latlng?
console.log("Point in lat,lng space: " + pointlatlng);
}
And a changed jsFiddle.
Also you can check the conversion methods that Leaflet offers for additional reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With