How can I have a circle marker or one of a selection of icons depending on a feature's properties using LeafletAjax?


function pointToLayer(feature, latlng){

var features = new L.GeoJSON.AJAX("/features.json?circuit=555",{
    pointToLayer: pointToLayer,


    style: function (feature) {
      return feature.properties && feature.properties.style;

I've started to try to build this, but Point to layer is only called once. The console log shows just the first feature's shape.

I have also tried to add the code to the onEachFeature function:

function onEachFeature(feature,layer){
    if (feature.properties.shape == 'point'){
    feature.marker =  L.circleMarker(latlng, {
      weight: 1,
      opacity: 1,
      fillOpacity: 0.8
  }else if(feature.properties.shape == 'tree'){
    feature.marker =  L.marker(latlng, {icon: treeIcon});

  if (feature.properties){

Which doesn't work - I have made up the "feature.marker =" bit.

How do I set the marker?

  • 1
    In pointToLayer, what happens if you insert return L.marker(latlng); into the function? What is the result? – Stefan Oct 29 '18 at 23:34
  • I get a marker for each Point in the geojson. Which led to other discoveries, and boom I got it working. Turns out, the bug was elsewhere. Not in the PointToLayer bit. Thanks for the nudge @Stefan_Fairphone – Will Oct 30 '18 at 18:13
  • Could you post a working example as an answer to your question? This will help others that have the same or a similar problem. – Stefan Oct 31 '18 at 11:43

To do this, I declare the icons and then just choose it based on a feature's properties.

function pointToLayer(feature, latlng){
    if (feature.properties.shape == 'point'){
        return L.marker(latlng, {icon: markerIcon});
    }else if(feature.properties.shape == 'tree'){
        return L.marker(latlng, {icon: treeIcon});
    }else if(feature.properties.shape == 'hazard'){
        return L.marker(latlng, {icon: hazardIcon});
    }else if(feature.properties.shape == 'log_pile'){
        return L.marker(latlng, {icon: logPileIcon});
        return L.marker(latlng, {icon: labelIcon});

To simplify @Will's answer using a switch-case statement:

function pointToLayer(feature, latlng){
    var icon
    switch (feature.properties.shape) {
        case 'point':   icon = markerIcon; break;
        case 'tree':    icon = treeIcon; break;
        case 'hazard':  icon = hazardIcon; break;
        case 'log_pile':icon = logPileIcon; break;
        default:        icon = labelIcon;
    return L.marker(latlng, {icon: icon})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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