- 動態繪點
- 動態繪線
- 動態繪多邊形
map = L.map("map-container").setView([51.505, -0.09], 8);
動態繪點
動態繪點就是在鼠標點擊位置添加一個固定半徑的圓
map.on('click',function(e){
L.circle(e.latlng,{radius:100,color:'red',fillColor:'red',fillOpacity:1}).addTo(map)
})
如果要繪制一個任意半徑的圓,整個過程分為三步:
- 鼠標按下:確定圓心
- 按住拖動鼠標:確定半徑
- 松開鼠標:繪制
代碼如下:
var r=0
var i=null
var tempCircle=new L.circle()
map.on('mousedown', onmouseDown);
map.on('mouseup',onmouseUp);
map.on('mousemove',onMove)
//map.off(....) 關閉該事件
function onmouseDown(e)
{
i=e.latlng
//確定圓心
}
function onMove(e) {
if(i) {
r = L.latLng(e.latlng).distanceTo(i)
tempCircle.setLatLng(i)
tempCircle.setRadius(r)
tempCircle.setStyle({color:'#ff0000',fillColor:'#ff0000',fillOpacity:1})
map.addLayer(tempCircle)
}
}
function onmouseUp(e)
{
r = L.latLng(e.latlng).distanceTo(i)//計算半徑
L.circle(i,{radius:r,color:'#ff0000',fillColor:'#ff0000',fillOpacity:1}).addTo(map)
i=null
r=0
}
動態繪線
動態繪線主要涉及到三個事件:click,dbclick,mousemove
click
確定線的折點,dbclick
確定線的終點,mousemove
繪制鼠標移動過程中圖形的變化。如果我們有一個地圖map
,動態繪線的代碼如下:
var points=[]
var lines=new L.polyline(points)
var tempLines=new L.polyline([])
map.on('click', onClick); //點擊地圖
map.on('dblclick',onDoubleClick);
//map.off(....) 關閉該事件
function onClick(e)
{
points.push([e.latlng.lat,e.latlng.lng])
lines.addLatLng(e.latlng)
map.addLayer(lines)
map.addLayer(L.circle(e.latlng,{color:'#ff0000',fillColor:'ff0000',fillOpacity:1}))
map.on('mousemove',onMove)//雙擊地圖
}
function onMove(e) {
if(points.length>0) {
ls=[points[points.length-1],[e.latlng.lat,e.latlng.lng]]
tempLines.setLatLngs(ls)
map.addLayer(tempLines)
}
}
function onDoubleClick(e)
{
L.polyline(points).addTo(map)
points=[]
lines=new L.polyline(points)
map.off('mousemove')
}
動態繪多邊形
動態繪多邊形同樣涉及到三個事件:click,dbclick,mousemove
,如果我們有一個地圖map
,動態繪制多邊形的代碼如下
var points=[]
var lines=new L.polyline([])
var tempLines=new L.polygline([])
map.on('click', onClick); //點擊地圖
map.on('dblclick',onDoubleClick);
map.on('mousemove',onMove)//雙擊地圖
//map.off(....) 關閉該事件
function onClick(e)
{
points.push([e.latlng.lat,e.latlng.lng])
lines.addLatLng(e.latlng)
map.addLayer(lines)
map.addLayer(L.circle(e.latlng,{color:'#ff0000',fillColor:'ff0000',fillOpacity:1}))
}
function onMove(e) {
if(points.length>0) {
ls=[points[points.length-1],[e.latlng.lat,e.latlng.lng]]
tempLines.setLatLngs(ls)
map.addLayer(tempLines)
}
}
function onDoubleClick(e)
{
L.polygon([points]).addTo(map)
points=[]
lines=new L.polyline([])
}
后記:關於leaflet的學習文檔可能短時間不會再更新了,基本的知識大家在文檔中都可以找到,更深奧的東西我現在也不會,以后在工作過程中學到我認為有用的新內容還會繼續更新,接下來我要學習另一個庫openlayers。