問題描述
我正在嘗試使用傳單地圖庫在單擊(右鍵單擊/上下文菜單)時獲取圖像疊加層的像素坐標.本質上,當用戶點擊圖片時,我需要找到用戶點擊圖片位置的 x、y 或寬度、高度.
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);
目前 onMapClick(e) 在檢查點擊返回的事件時,我看不到所有返回坐標的證據,任何靠近我點擊位置的 x、y 或寬度和高度.
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.
鑒于圖像的尺寸為 20000x15000,基本上我想看到的是我單擊的圖像位置的 x、y 或寬度、高度.
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.
這里是小提琴 http://jsfiddle.net/rayshinn/yvfwzfw4/1/
不知道為什么,但是當您一直放大時,它似乎有點錯誤.只需一直放大它就可以阻止 jsfiddle 上的錯誤.這個錯誤不是重點,因為它不會發生在我的本地環境中!似乎和小提琴有關.
推薦答案
傳單為您提供沿image-map" div 的 x,y 坐標,該坐標會隨著放大和縮小而調整大小.事件坐標不會縮放到您的圖像大小.
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.
為了獲得相對于實際圖片大小的 x,y,您需要將坐標乘以 當前 div 尺寸與全尺寸圖片的比率 尺寸.
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.
我通過獲取事件坐標,將它們乘以您的 var w
和 var h
并除以地圖的高度和寬度來計算您的 x,y:
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);
}
這篇關于單擊(右鍵單擊)使用傳單地圖庫獲取圖像疊加層的像素坐標的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!