Change Leaflet marker icon with data from external geoJSON file

I have a problem at changing the icons of my geoJSON data on my Leaflet map.

I’m loading my data from external geoJSON files. Therefore I’m using a XMLHttpRequest() to open the files (filenames are stored in an array orteDB) and then add them to my layer orte where it’s then added to the map:

for (var i = 0; i < orteDB.length; i++) {
    let xhr = new XMLHttpRequest();'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);

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

I already managed to change the default icon with the help of this example But what I actually want is the icon to change dynamically after the click of a button or the marker itself to this redIcon:

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

I also tried working with the pointToLayer() function but it didn’t work for me.

Each geoJSON point has a unique ID which I can call via So in the end I’d like to change the marker icon individually by using it’s unique ID.

My geoGSON files look like this:

 "type": "FeatureCollection",
 "name": "02_Roncesvalles",
 "features": [
   "type": "Feature", 
      "id": 2 }, 
      "coordinates": [ 
        43.009378247303687 ] 

Thank you very much for your help!

7 thoughts on “Change Leaflet marker icon with data from external geoJSON file”

Leave a Comment