問題描述
在 Leaflet 上,給定中心和半徑,我可以輕松創建一個新圓:
On Leaflet I can create a new circle easily given the centre and the radius:
// 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);
上面的圓圈創建和繪制沒有問題,所以就是這樣.
The circle above is created and drawn without problems, so it is all.
但是,如果我現在想創建并繪制一個與圓為界的矩形,它就行不通了.這是我所做的:
However, if I wanted now to create and draw a rectangle that which bounds the circle, it does not work. Here is what I did:
// 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米無關.此外,看起來矩形的大小取決于地圖的縮放級別.圈子沒有出現這些問題.
The size of the rectangle that I obtain has nothing to do with 500 metres. Also, it looks like the size of the rectangle depends on the zoom level the map is. None of these problems arose for the circle.
我懷疑我將緯度/經度轉換為點的方式是錯誤的,反之亦然.
I suspect the way I transform the latitude/longitude to point and viceversa is wrong.
推薦答案
使用L.Circle
繼承自L.Path
getBounds方法即可代碼>:
Just use the getBounds
method that L.Circle
inherits from L.Path
:
返回路徑的 LatLngBounds.
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
Working example on Plunker: http://plnkr.co/edit/n55xLOIohNMY6sVA3GLT?p=preview
這篇關于傳單正方形給定中心和正方形寬度的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!