在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米无关。另外,矩形的大小取决于地图的缩放级别。这些问题都没有出现。

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

最佳答案

只需使用getBoundsL.Circle继承的L.Path方法:


  返回路径的LatLngBounds。


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

08-18 13:26