簡體   English   中英

將數據屬性添加到leaflet.js標記元素

[英]Add data attribute to leaflet.js marker element

目標:將數據屬性添加到leaflet.js標記元素標記

我有一個帶有地圖和“聚光燈”區域的項目。

使用leaflet.js使用位置填充地圖

當我點擊地圖上的一個圖釘時,我希望它的相應圖像和信息出現在聚光燈區域。

我做了一個沒有地圖的初步測試: http//codepen.io/sheriffderek/pen/yOmjLV我使用數據歸因於連接硬幣的兩面。 (一組數據由PHP吐出,地圖數據是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屬性。

第一:閱讀傳單代碼 如果你花一點時間,很容易理解。 對於標記,HTML實際上是在L.IconL.Icon ,而不是在L.MarkerL.Marker

完成后,您會注意到src/layer/marker/icon.js中的代碼src/layer/marker/icon.js操作:

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

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

如果您隨后閱讀了Leaflet的插件指南 ,那么您將意識到您可以制作以下行中的插件:

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;
        }
    }

});

你應該能夠從那里解決它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM