Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapbox set icon for featureLayer

Tags:

leaflet

mapbox

I am having some problems with setting an icon for a feature layer. I keep getting layer.setIcon is not a function and similar errors. How can I change the icon style for this layer?

 var layer = L.mapbox.featureLayer()
            .loadURL(attrs.geoJsonSource)
            .addTo(map);

        layer.on('ready', function() {
            this.eachLayer(function(layer){
                layer.setIcon(L.mapbox.marker.icon({
                    'marker-color': '#8834bb',
                    'marker-size': 'large',
                    'marker-symbol': 'restaurant'
                }))
            });
            map.fitBounds(featureLayer.getBounds());
        });
like image 431
Jan-Willem Gmelig Meyling Avatar asked Sep 21 '16 12:09

Jan-Willem Gmelig Meyling


1 Answers

You can take a look at https://www.mapbox.com/mapbox.js/example/v1.0.0/custom-marker/ and http://leafletjs.com/examples/custom-icons/ to get more information, but apparently you may fit your need:

  • using your own icon style. (FIRST)

and/or

  • using geoJSON file icon style. (SECOND)

The code:

var map = L.mapbox.map('map', 'mapbox.streets').setView([40, -74.50], 9);
var layer = L.mapbox.featureLayer().addTo(map);

layer.on('layeradd', function(e) {
    var marker = e.layer,feature = marker.feature;

    // TWO POSSIBILITIES

    // FIRST // your own method to define how icon will be rendered   
    marker.setIcon(L.mapbox.marker.icon({
        'marker-color': '#8834bb',
        'marker-size': 'large',
        'marker-symbol': 'restaurant' 
    }));

    // SECOND // use json directly to define how icon will be rendered   
    //marker.setIcon(L.mapbox.marker.icon(feature.properties.icon));
});

layer.setGeoJSON(geoJson);

assuming the geoJSON file look like this:

var geoJson = [{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [-75.00, 40]
    },
    "properties": {
        "title": "Small astronaut",
        "icon": {
            'marker-color': '#0034bb',
            'marker-size': 'large',
            'marker-symbol': 'restaurant' 
        }
    }
}, {
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [-74.00, 40]
    },
    "properties": {
        "title": "Big astronaut",
        "icon": {
            'marker-color': '#8834bb',
            'marker-size': 'large',
            'marker-symbol': 'restaurant' 
        }
    }
}];
like image 158
A STEFANI Avatar answered Oct 13 '22 10:10

A STEFANI