我有一张地图和一个区域选择字段:
// initialize map
var map = L.map('map').setView([38, 0], 2);
L.tileLayer('http://{s}.tile.cloudmade.com/70146506bc514228adc1756788c730d3/997/256/{z}/{x}/{y}.png', {attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, Imagery © <a href="http://cloudmade.com">CloudMade</a>', maxZoom: 18}).addTo(map);
var areaSelect = L.areaSelect({
width:100,
height:150,
keepAspectRatio:true
});
areaSelect.addTo(map);
areaSelect.setDimensions({width: 50, height: 50});
想获得矩形的宽度和高度。
var neLatCoord = $('#ne-lat-coordinate').val();
var neLonCoord = $('#ne-lon-coordinate').val();
var swLatCoord = $('#sw-lat-coordinate').val();
var swLonCoord = $('#sw-lon-coordinate').val();
var rectangle = L.rectangle([ [neLatCoord, neLonCoord], [swLatCoord, swLonCoord]]).addTo(map);
所以现在我想得到矩形的宽度和高度,所以我可以设置区域的尺寸选择如下:
var rectangleWidth = rectangle.getBounds().getEast() - rectangle.getBounds().getWest();
var rectangleHeight = rectangle.getBounds().getNorth() - rectangle.getBounds().getSouth();
areaSelect.setDimensions({width: rectangleWidth, height: rectangleHeight});
但这会给出另一个宽度和高度?我不知道为什么?
有人可以帮助我,因为我被困在这上面了吗?
这是我的JS FIDDLE
编辑:
如果我使用矩形而不是区域选择:
var rectangle = L.rectangle([ [21.616579, 29.487305], [7.798079, 20.522461]]);
map.addLayer(rectangle);
rectangle.editing.enable();
// Every time we move the selected rectangle, refresh data about the selected area.
rectangle.on('edit', function() {
selectedBounds = this.getBounds();
console.log("Area:", selectedBounds);
//some other code
});
$( ".select" ).click(function() {
rectangle.editing.disable();
map.removeLayer(rectangle);
rectangle = new L.rectangle([ [17.853290, 34.980469], [10.876465, 14.853516]]);
map.addLayer(rectangle);
rectangle.editing.enable();
});
当我在点击时执行此重置时,事件rectangle.on('edit', function() { ...
无效?我不知道为什么?你能帮帮我吗
答案 0 :(得分:2)
与leaflet-areaselect状态中的docs一样,方法.setDimensions()
需要参数作为Pixel,并且您在地理坐标中给出参数。使用leaflet map method .latLngToLayerPoint()
,您可以转换geogr。 coords to the Pixel of the map of extend。
只需更改
var rectangleWidth = rectangle.getBounds().getEast() - rectangle.getBounds().getWest();
var rectangleHeight = rectangle.getBounds().getNorth() - rectangle.getBounds().getSouth();
到
var rectangleWidth = map.latLngToLayerPoint(rectangle.getBounds().getNorthEast()).x- map.latLngToLayerPoint(rectangle.getBounds().getSouthWest()).x
var rectangleHeight = map.latLngToLayerPoint(rectangle.getBounds().getNorthEast()).y- map.latLngToLayerPoint(rectangle.getBounds().getSouthWest()).y
这是工作JS FIDDLE
答案 1 :(得分:2)
我知道这个帖子大约有一年的历史,但我认为其他人可能会因为我提供的答案的麻烦而受益。
Leaflet实际上提供了2种转换方法:
两者之间的差异与如何计算x,y位置有关。
LayerPoint 在初始化时找到相对于地图的左上角的x,y位置!!! (缩放重置此原点,但平移不会!)
ContainerPoint 找到相对于地图容器本身左上角的x,y位置。
为什么重要?
如果您初始化地图,平移它,然后使用 latLngToLayerPoint()获取x,y坐标,则可能会获得负x / y值,如果可能导致负宽度/高度你没有积极地补偿它们。
至少在我的用例中,最好在确定边界高度/宽度(以像素为单位)时使用 latLngToContainerPoint()。
除此之外,上面的答案对我来说非常合适! :d