首页 > 解决方案 > 如何使用传单定位控件中的“createButtonCallback”

问题描述

我想将leaflet-locatecontrol插件中的默认定位按钮替换为侧边栏内的div元素中的另一个按钮(leaflet sidebar v2)。

这是一个例子: https ://vprint.github.io/#14/13.4413/103.8591

我想要做的是当我单击使用此行创建的左侧位置按钮(左侧边栏上的那个)时调用定位函数

<li class="disabled">

    <a href="#locate" role="tab" onclick="LocateMe()">
        <i class="fas fa-map-marker-alt"></i>
    </a>

</li>

我在定位插件文档中看到了“CreateButtonCallback”选项,但是如何使用它来解决我的问题?

我找到的唯一文档是这个,但我不明白:

/**
* This callback can be used in case you would like to override button creation behavior.
* This is useful for DOM manipulation frameworks such as angular etc.
* This function should return an object with HtmlElement for the button (link property) and the icon (icon property).
*/
createButtonCallback: function (container, options) {
   var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
   link.title = options.strings.title;
   var icon = L.DomUtil.create(options.iconElementTag, options.icon, link);
   return { link: link, icon: icon };
},

标签: javascripthtmlleafletsidebar

解决方案


回答我自己的问题:

我终于找到了遵循这个技巧的解决方案:将 Leaflet layer control 添加到侧边栏

如果你想在侧边栏(或任何其他插件)中添加位置控制,你必须在 li 类中创建一个 div 元素,如下所示:

HTML

<li class="disabled">
  <a href="#LocateMe" role="tab">
    <div id="#LocateMe"></div>
   </a>
</li>

然后修改JS

JS

var positioncontrol = L.control.locate({
   position: 'topleft',
   showCompass: true,
   strings: {title: "Location"},
   icon: 'fas fa-map-marker-alt',
   locateOptions: {enableHighAccuracy: true}
}).addTo(map);

var htmlObject = positioncontrol.getContainer();
var a = document.getElementById('#LocateMe')
function setParent(el, newParent){
  newParent.appendChild(el);
}
setParent(htmlObject, a);

然后您必须编辑 CSS,使其与侧边栏很好地匹配


推荐阅读