Leaflet地图使用自定义控件

来更新一下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官方文档上用到了这些

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值