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

use*_*709 0 javascript latitude-longitude leaflet 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);
Run Code Online (Sandbox Code Playgroud)

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

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

// 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);
Run Code Online (Sandbox Code Playgroud)

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

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

iH8*_*iH8 5

只需使用继承自的getBounds方法:L.CircleL.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);
Run Code Online (Sandbox Code Playgroud)

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