目标:将数据属性添加到leaflet.js标记元素标记

我有一个带有 map 和“聚光灯”区域的项目。

使用leaflet.js在 map 上填充位置

当我单击 map 上的图钉时,我希望它的对应图像和信息出现在聚光灯区域。

我进行了没有 map 的初步测试:http://codepen.io/sheriffderek/pen/yOmjLV我使用归因数据连接硬币的两面。 (PHP吐出了一组数据,而 map 数据是一个API ajax调用)

我认为添加类或ID或数据或rel等将是一个可访问的选项。这是它的实质:

// Purveyor types - for query endpoints
var bar = 4;
var retailer = 3;

// Create the "map"
var onSiteMap = L.map('on-site-map').setView([34.0758661, -118.25430590], 13);

// Define the pin (no SVG?)
var onSiteIcon = L.divIcon({
  className: 'my-div-icon' // this gets one class name as far as I can tell
});

// Setup map "Look"
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(onSiteMap);

// Grab the data
$.ajax( {
  url: 'http://xxxxxx.com/wp-json/wp/v2/purveyor?purveyor-type=' + bar,
  success: function ( data ) {
    var purveyorData = data;
    for (var i = 0; i < data.length; i++) {
      var ourLat = purveyorData[i].acf.purveyor_latitude;
      var ourLong = purveyorData[i].acf.purveyor_longitude;
      var ourSlug = purveyorData[i].slug;
      // create the markers
      L.marker([ ourLat , ourLong ], {
        icon: onSiteIcon,
        slug: ourSlug // creates an extra option... but...
      }).addTo(onSiteMap);
    }
  },
  cache: false
});

我可以为对象添加一个“选项”和一个唯一的值,但这并不能帮助我将某些东西添加到标记中。

标记的元素最终如下所示:
<div
    class="leaflet-marker-icon my-div-icon leaflet-zoom-animated leaflet-clickable"
    tabindex="0" style="margin-left: -6px; margin-top: -6px; width: 12px; height: 12px; transform: translate3d(276px, 140px, 0px); z-index: 140;"></div>

试图得到更多这样的东西:
<div
    id='possible-id-237'
    rel='possible-rel'
    data-name='this-slug'
    class="leaflet-marker-icon my-div-icon leaflet-zoom-animated leaflet-clickable"
    tabindex="0" style="margin-left: -6px; margin-top: -6px; width: 12px; height: 12px; transform: translate3d(276px, 140px, 0px); z-index: 140;"></div>

我研究了一下-大多数问题都在2014年或更早。希望新文档中缺少我想要的东西。

最佳答案



没错-Leaflet不会神奇地将选项转换为HTML data属性。

首先:阅读leaflet code!如果您花一些时间,这很容易理解。对于标记,HTML实际上是在L.Icon中构建的,而不是在L.Marker中构建的。

完成此操作后,您会注意到src/layer/marker/icon.js中的代码执行以下操作:

_setIconStyles: function (img, name) {
    var options = this.options;

    if (options.something) {
        img.style.something = something(something);
    }
},

如果您随后阅读Leaflet's plugin guide,那么您将意识到可以按以下方式制作一个插件:
L.Icon.DataMarkup = L.Icon.extend({

    _setIconStyles: function(img, name) {
        L.Icon.prototype._setIconStyles.call(this, img, name);

        if (options.slug) {
            img.dataset.slug = options.slug;
        }
    }

});

您应该能够从那里解决问题。

关于javascript - 将数据属性添加到leaflet.js标记元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37782930/

10-10 17:03
查看更多