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

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);


}

To solve this problem you need to utilize the map project to convert the latitude and longitude to coordinates in the image.

The Project method on the map is the magic

http://leafletjs.com/reference.html#map-conversion-methods

The projection will give you the X,Y in the image. These values will be zoomed based on how the image is scaled (i.e. the map zoom level).

Calculating the natural (X,Y) of the click is just a matter of calculating the scale ratio of the map bounds or overlay size and then dividing that by the projected click coordinates.

  1. When you create the imageOverlay store that in a variable. Need to reference that to determine the scale factor of the image layer.

  2. On click project the lat lng of the click into (x,y) coordinates

  3. divide current width and height of the image with the natural width and height (you need to do this to handle the size change caused by map zoom)

  4. Divide projected click coordinates by the scale factor. This will give you back the actually X,Y coordinates in the original image which is what I think you want. Code below and check out the fiddle for working example. http://jsfiddle.net/muglio/h5st7bpt/

.

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

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

function onMapClick(e) {
    //Project the map click to x,y coordinates
    //This projection is the actual XY coordinates of the image layer
    //This coordinate is scaled by the amount the image is zoomed.
    var clientClick = map.project(e.latlng);

    //Grab the original overlay
    var overlayImage = overlay._image;

    //Calculate the current image ratio from the original (deals with zoom)
    var yR = overlayImage.clientHeight / overlayImage.naturalHeight;
    var xR = overlayImage.clientWidth / overlayImage.naturalWidth;

    //scale the click coordinates to the original dimensions
    //basically compensating for the scaling calculated by the map projection
    var x = clientClick.x / xR;
    var y = clientClick.y / yR;
    console.log(x,y);
}

Hope this helps!