来更新一下leaflet,最近又出了一个新需求:使用leaflet框架自带的控件去做一个地图搜索定位的功能,我找了半天找到了一个自定义控件可以满足需求
initMap(){
L.Control.Search = L.Control.extend({
options: {
position: 'topleft' //初始位置
},
initialize: function(options) {
L.Util.extend(this.options, options)
},
onAdd: function(map) {
var _that = that
console.log('ddddddd', this)
//创建Dom元素=== L.DomUtil.create('元素类型', '元素类名')
this._container = L.DomUtil.create('div', 'leaflet-control-container') //创建一个主元素
var inp = L.DomUtil.create('div', 'leaflet-control-input')
var btn = L.DomUtil.create('button', 'leaflet-control-button')
//设置Dom元素的内容
// inp.id='inp' //可以为元素设置id
inp.innerHTML = ' <input placeholder="天安门" ref="a" id="boox" style="width:150px;margin-right:20px;" /> '
btn.innerText = '搜索'
//将元素添加到主元素上
this.inpLeaflet = inp
this.btnLeaflet = btn
this.btnLeaflet.onclick = _that.searchMap //为button按钮添加点击事件
this._container.style.display = 'flex'
this._container.appendChild(this.inpLeaflet)
this._container.appendChild(this.btnLeaflet)
//返回这个主元素
return this._container
}
})
//在L.control上添加一个search(封装好的函数)
L.control.Search = function(options) {
return new L.Control.Search(options)
}
//将自定义控件添加到地图上
L.control.Search().addTo(this.map)
}
要注意这里的this指向的是map实例,并且还有一个坑:在自定义控件扩展函数中不能使用js原生方法获取到dom实例,但是我却要获取到input框中用户输入的内容,可以在searchMap 函数中添加如下代码
console.log('querySelector', document.querySelector('#boox').value)
console.log('getElementById', document.getElementById('boox').value)
在leaflet官方文档上用到了这些