Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting pixel coordinates of an image overlay using leaflet map library on click (right click)

I'm trying to get the pixel coordinates of an image overlay on click (right click/contextmenu) using the leaflet map library. Essentially when a user clicks on the image, I need to find the x,y or width,height of where the user clicked on the image.

Currently this is what I have.

// Using leaflet.js to pan and zoom a big image.
// See also: http://kempe.net/blog/2014/06/14/leaflet-pan-zoom-image.html

// create the slippy map
var map = L.map('image-map', {
    minZoom: 1,
    maxZoom: 4,
    center: [0, 0],
    zoom: 1,
    crs: L.CRS.Simple,
});

// dimensions of the image
var w = 2000,
    h = 1500,
    url = 'http://kempe.net/images/newspaper-big.jpg';

// calculate the edges of the image, in coordinate space
var southWest = map.unproject([0, h], map.getMaxZoom() - 1);
var northEast = map.unproject([w, 0], map.getMaxZoom() - 1);
var bounds = new L.LatLngBounds(southWest, northEast);

// add the image overlay, 
// so that it covers the entire map
L.imageOverlay(url, bounds).addTo(map);

// tell leaflet that the map is exactly as big as the image
map.setMaxBounds(bounds);

function onMapClick(e) {

 //returns on right click events   
 console.log(e);


}

//Hadnel on right click functions TODO: MOVE THIS LATER
map.on('contextmenu', onMapClick);

Currently onMapClick(e) upon inspecting the returned events on click I see no evidence of all returned coordinates any where near to the x,y or width and height of the location I clicked.

Essentially what I would like to see is the x,y or width,height of the location of the image I clicked given that the image is 20000x15000 in dimension.

Here is the fiddle http://jsfiddle.net/rayshinn/yvfwzfw4/1/

Not sure why but it's seems a bit buggy when you zoom all the way out. Just zoom all the way in for it to stop the bug on jsfiddle. This bug is not the focus as it does not happen in my local environment! seems to be something to do with fiddle.

like image 574
BaconJuice Avatar asked Apr 07 '15 15:04

BaconJuice


1 Answers

The leaflet is giving you the x,y coordinates along the "image-map" div which resizes with the zoom in and out. The event coordinates do not scale to your image size.

In order to get x,y relative to actual picture size, you need to multiply the coordinates against the ratio of current div dimensions and full sized image dimensions.

Check my Fiddle

I calculated your x,y by taking the events coordinates, multiplying them by your var w and var h and dividing them by the maps height and width:

function onMapClick(e) {

    var mapWidth=map._container.offsetWidth;
    var mapHeight=map._container.offsetHeight;
    console.log(e.containerPoint.x * w / mapWidth);
    console.log(e.containerPoint.y * h / mapHeight);
    console.log(e);


}
like image 50
Dave Alperovich Avatar answered Sep 21 '22 13:09

Dave Alperovich