1

I am trying to define a new icon for my points in Leaflet but am drawing a blank. I am using Fetch (see code) to access the data and have it displayed with the default icon but can't work out how to change it to another within the fetch. Thanks.

    let puburl = "http:...
    let pubIcon = new L.icon({
      iconUrl: 'markers/beer.png'
    });

    fetch(puburl)
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            L.geoJSON(data, {
                onEachFeature: function(feature, layer) {
                    layer.bindPopup("<a href='" + feature.properties.URL + "'>" + feature.properties.PubName + "</a>")
                }
            }).addTo(map);
        }); 

1 Answer 1

2

You must specify pointToLayer in the L.geoJSON call:

A Function defining how GeoJSON points spawn Leaflet layers. It is internally called when data is added, passing the GeoJSON point feature and its LatLng. The default is to spawn a default Marker:

function(geoJsonPoint, latlng) {
    return L.marker(latlng);
}

In your case it would look like this:

L.geoJSON(data, {
  onEachFeature: {...},
  pointToLayer: function(point, latlng) {
    return L.marker(latlng, { icon: pubIcon })
  }
})
1
  • Thanks Stefan, very much appreciated.
    – Jim Norton
    Commented Apr 6, 2020 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.