Leaflet非地理地图拖动标记时如何显示图像像素坐标而非经纬度
解决方案
要实现拖动标记时显示原始图像的像素坐标,你可以利用rastercoords.js提供的project()方法,将Leaflet的经纬度坐标转换为图像的像素坐标。具体修改步骤如下:
核心修改点
在标记的dragend事件处理函数中,替换原本获取经纬度的逻辑,改用rc.project()方法转换坐标:
marker.on('dragend', function (e) { // 获取标记的经纬度坐标 const latLng = marker.getLatLng(); // 将经纬度转换为原始图像的像素坐标 const pixelCoords = rc.project(latLng); // 赋值到对应的输入框(请替换为你实际的像素坐标输入框ID) document.getElementById('PixelX').value = Math.round(pixelCoords[0]); document.getElementById('PixelY').value = Math.round(pixelCoords[1]); });
完整修改后的index.js代码
;(function(window) { // use below if you want to specify the path for leaflet's images //L.Icon.Default.imagePath = '@Url.Content("~/Content/img/leaflet")'; function init (mapid) { var minZoom = 1 var maxZoom = 5 var img = [ 4129, // original width of image `karta.jpg` 4608 // original height of image ] // create the map var map = L.map(mapid, { minZoom: minZoom, maxZoom: maxZoom }) // assign map and image dimensions var rc = new L.RasterCoords(map, img) // set the view on a marker ... map.setView(rc.unproject([2065, 2304]), 4) var curLocation = [0, 0]; // use below if you have a model // var curLocation = [@Model.Location.Latitude, @Model.Location.Longitude]; if (curLocation[0] == 0 && curLocation[1] == 0) { curLocation = rc.unproject([2065, 2304]); } // the tile layer containing the image generated with gdal2tiles --leaflet ... L.tileLayer('./tiles/{z}/{x}/{y}.png', { noWrap: true, attribution:'<a href="gamearena.ro">GAME ARENA</a>' }).addTo(map) map.attributionControl.setPrefix(false); var marker = new L.marker(curLocation, { draggable: 'true' }).addTo(map); marker.on('dragend', function (e) { const latLng = marker.getLatLng(); const pixelCoords = rc.project(latLng); // 替换成你实际的像素坐标输入框ID document.getElementById('PixelX').value = Math.round(pixelCoords[0]); document.getElementById('PixelY').value = Math.round(pixelCoords[1]); }); } init('map') }(window))
关键说明
rc.project(latLng):该方法会将Leaflet的地理坐标(LatLng)反向转换为原始图像的像素坐标,返回格式为[x, y],其中x对应图像的横向像素(范围0到4129),y对应纵向像素(范围0到4608)。Math.round():转换后的坐标可能带有小数,取整后得到符合需求的整数像素值。- 输入框ID:请根据你实际的HTML输入框ID修改
PixelX和PixelY,如果原来的输入框是Latitude和Longitude,直接替换ID即可。
内容的提问来源于stack exchange,提问作者mThemes Net
相关产品推荐
相关产品推荐

