如何将自定义UI添加到传单地图?

时间:2018-01-17 00:20:46

标签: leaflet

我正在使用Leaflet创建一个地图游戏(非常基本)。

基本上我想在地图上添加输入<div>,这样当用户输入某个位置时,它会平移到地图上的坐标。

我尝试过创建元素并附加到地图<div>,其变体为:

var d1 = document.getElementsByClassName('leaflet-control-container')[0]; 

d1.insertAdjacentHTML('afterbegin', '<div id="two">two</div>');

<div>显示在地图后面,图像覆盖了它。

如何让它像缩放控件一样显示?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望创建自己的“控件”(在某种程度上与Leaflet默认的缩放控件类似,但具有不同的功能),这将允许查找不同的位置并导航到它们。

对于类似于Leaflet默认控件(缩放,图层控件)的控件样式,您需要:

  1. 延长L.Control
  2. 指定一个onAdd方法,该方法返回要在地图上用作Control的DOM元素。步骤1和2将使您的Control可添加到地图角落作为标准控件,具有适当的z-index和边距。
  3. 使用您自己的班级设计它。要获得类似于缩放和图层控件的视觉效果,您可以构建leaflet-bar类:
  4. .leaflet-bar {
      box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);
      border-radius: 5px;
    }
    

    示例:(源自“Extending Leaflet: Handlers and Controls”教程)

    var map = L.map('map').setView([48.86, 2.35], 11);
    
    L.Control.MyControl = L.Control.extend({
      onAdd: function(map) {
        var el = L.DomUtil.create('div', 'leaflet-bar my-control');
    
        el.innerHTML = 'My Control';
    
        return el;
      },
    
      onRemove: function(map) {
        // Nothing to do here
      }
    });
    
    L.control.myControl = function(opts) {
      return new L.Control.MyControl(opts);
    }
    
    L.control.myControl({
      position: 'topright'
    }).addTo(map);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    .my-control {
      background: #fff;
      padding: 5px;
    }
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.0/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.3.0/dist/leaflet-src.js" integrity="sha512-2h9aokfcaYW7k0VPn1JqbQDQCaNQRrZJwetlnQ88yJrtIzGLVW/2StdQKoE+TIVNNTUxf6SVa+2vW2KB2EXnnA==" crossorigin=""></script>
    
    <div id="map" style="height: 200px"></div>

    话虽如此,您希望实现的控制功能听起来与Leaflet Control Search插件(又名“传单搜索”)非常相似

      

    通过自定义属性搜索标记/要素位置的Leaflet控件。

相关问题