簡體   English   中英

使用外部 geoJSON 文件中的數據更改 Leaflet 標記圖標

[英]Change Leaflet marker icon with data from external geoJSON file

我在更改 Leaflet map 上的 geoJSON 數據圖標時遇到問題。

我正在從外部 geoJSON 文件加載我的數據。 因此,我使用XMLHttpRequest()打開文件(文件名存儲在數組orteDB ),然后將它們添加到我的層orte ,然后將其添加到 map:

for (var i = 0; i < orteDB.length; i++) {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'files/geoJSONfiles/orte/' + orteDB[i]);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.responseType = 'json';
    xhr.onload = function () {
        if (xhr.status !== 200) return
        L.geoJSON(xhr.response).addTo(orte).on('click', onClick);
    };
    xhr.send();
}

orte = L.geoJson(orte).addTo(map);

我已經設法借助此示例https://gist.github.com/geog4046instructor/80ee78db60862ede74eacba220809b64更改默認圖標。 但我真正想要的是在單擊按鈕或標記本身到此redIcon后動態更改的圖標:

var redIcon = L.Icon.extend({
        iconUrl: 'files/marker-icon_red.png',
        iconSize:     [25, 41],
        iconAnchor:   [12, 40],
    });

我也嘗試使用pointToLayer() function 但它對我不起作用。

每個 geoJSON 點都有一個唯一的 ID,我可以通過e.layer.feature.properties.id調用它。 所以最后我想通過使用它的唯一 ID 單獨更改標記圖標。

我的 geoGSON 文件如下所示:

{
 "type": "FeatureCollection",
 "name": "02_Roncesvalles",
 "features": [
  { 
   "type": "Feature", 
   "properties": 
     { 
      "id": 2 }, 
   "geometry": 
     { 
      "type":"Point", 
      "coordinates": [ 
        -1.320700314538876, 
        43.009378247303687 ] 
     } 
   }
  ]
}

非常感謝您的幫助!

您可以使用marker.setIcon(icon)更改標記的圖標,您需要遍歷所有層並在 id 上找到正確的層。

我使用map.eachLayer而不是orte.eachLayer()因為 GeoJSON Group 也可以包含 LayerGroups。

var wantedId = 1;
map.eachLayer((layer)=>{
   if(layer instanceof L.Marker && layer.feature && layer.feature.properties && layer.feature.properties.id == wantedId){
      layer.setIcon(new redIcon());
   }
});

更新

謝謝@ghybs,我沒認出圖標的extend

如果你想擴展圖標 class 你需要將選項放在options屬性中。

var redIcon = L.Icon.extend({
   options: {
        iconUrl: 'files/marker-icon_red.png',
        iconSize:     [25, 41],
        iconAnchor:   [12, 40],
   }
});

然后您可以使用marker.setIcon(new redIcon())更改圖標

但我建議您簡單地創建一個圖標變量,而不是創建一個新的 class。

var redIcon = L.icon({
        iconUrl: 'files/marker-icon_red.png',
        iconSize:     [25, 41],
        iconAnchor:   [12, 40],
    });

然后調用marker.setIcon(redIcon)

暫無
暫無

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

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