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

leaflet square given centre and square width

在 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米无关。此外,看起来矩形的大小取决于地图的缩放级别。 None 个问题出现在圆圈中。

我怀疑我将 latitude/longitude 转换为点和反之亦然的方式是错误的。

只需使用 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

我收到“无法读取未定义的 属性 'layerPointToLatLng'”错误,所以我对 iH8 的答案做了一些更改。

var grp=L.featureGroup().addTo(map);
var circle=L.circle([0,0],{radius:<circle radius>}).addTo(grp);
L.rectangle(circle.getBounds()).addTo(this.bufferMap);
map.removeLayer(grp);