javascript - 给定中心和正方形宽度的传单正方形

标签 javascript leaflet latitude-longitude angular-leaflet-directive

在Leaflet上,我可以根据中心和半径轻松创建一个新圆:

// Circle
var radius = 500; // [metres]
var circleLocation = new L.LatLng(centreLat, centreLon);
var circleOptions = {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5
};
var circle = new L.Circle(circleLocation, radius, circleOptions);
map.addLayer(circle);

上面的圆圈创建和绘制没有问题,所以就这样了。

但是,如果我现在想创建并绘制一个包围圆的矩形,则它不起作用。这是我所做的:

// Rectangle
var halfside = radius;   // It was 500 metres as reported above
// convert from latlng to a point (<-- I think the problem is here!)
var centre_point = map.latLngToContainerPoint([newCentreLat, newCentreLon]);
// Compute SouthWest and NorthEast points
var sw_point = L.point([centre_point.x - halfside, centre_point.y - halfside]);
var ne_point = L.point([centre_point.x + halfside, centre_point.y + halfside]);
// Convert the obtained points to latlng
var sw_LatLng = map.containerPointToLatLng(sw_point);
var ne_LatLng = map.containerPointToLatLng(ne_point);
// Create bound
var bounds = [sw_LatLng, ne_LatLng];
var rectangleOptions = {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5
};
var rectangle = L.rectangle(bounds, rectangleOptions);
map.addLayer(rectangle);

我得到的矩形的大小与500米无关。此外,看起来矩形的大小取决于 map 的缩放级别。对于圈子来说,这些问题都没有出现。

我怀疑我将纬度/经度转换为点的方式是错误的,反之亦然。

最佳答案

只需使用L.Circle继承自L.PathgetBounds方法即可:

Returns the LatLngBounds of the path.

http://leafletjs.com/reference.html#path-getbounds

var circle = new L.Circle([0,0], 500).addTo(map);

var rectangle = new L.Rectangle(circle.getBounds()).addTo(map);

Plunker 上的工作示例:http://plnkr.co/edit/n55xLOIohNMY6sVA3GLT?p=preview

关于javascript - 给定中心和正方形宽度的传单正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206206/

相关文章:

r - 使用 rCharts 在 r 和shiny中创建传单热图

javascript - Leaflet.js 在同一页面上动态多个 map

sql - 在SQL SERVER中使用Long和Lat计算点之间的距离

javascript - 数组有项目,但找不到长度

javascript - 启动mongodb和express的正确方法?

javascript - 单击具有与文本匹配的相同类的元素并退出 Protractor

javascript - 两个嵌套指令的链接函数执行顺序不一致

leaflet - 如何获取control.layers中选定的图层?

android - locationManager.getLastKnownLocation() 返回 null

c# - 从十进制度转换为度分秒十分之一。