2
votes

I'm building a leaflet map using GeoJSON data. I run into problems when trying to set the icon I use based on a GeoJSON property. I think my error is related to calling an object with a string, but I can't figure out what it is exactly.

Here's my code:

Each item in the GeoJSON has an iconcategory property as below :

{"type":"Feature",
    "properties":{
        "iconcategory": "iconGreyHouse",
            ...

For each icon category there's an icon variable as follows :

var iconGreyHouse = L.icon({
    iconUrl: "/markerIcons/house_icon_grey.png",
    iconSize: [20, 20]
});

Finally, when I load my GeoJSON file, I get "iconcategory" from my GeoJSON properties in the hopes of picking the corresponding icon variable...

$.getJSON("/GeoJSON/housemarkers.geojson", function (houses) {
    L.geoJson(houses, {
        pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {
                icon: feature.properties.iconcategory
            });
        }
    }).addTo(housemarkers);
});

This is where it doesn't work! If I use the exact same code but specify an icon variable name directly, all works fine; it's only when I try to set the icon via the feature.property that it fails.

1

1 Answers

3
votes

What happens here is that your passing a string not the icon instance. If you want to use a string to access javascript object properties you'll need to use bracket notation to access properties in a certain scope. If it's in global scope you could use: window[feature.properties.iconcategory] or this[feature.properties.iconcategory] but i'd recommend storing it a separate object. If you would do something like this:

var icons = {
    'iconGreyHouse' = L.icon({iconUrl: "/markerIcons/house_icon_grey.png",iconSize: [20,20]}),
    'iconRedHouse' = L.icon({iconUrl: "/markerIcons/house_icon_red.png",iconSize: [20,20]}),
    ...
}

You could call them like this: icons[feature.properties.iconcategory] or icons['iconGreyHouse']

Here's some reading if you're interested, there's also lots to find here on Stackoverflow if you search for javascript "property accessors" and/or "bracket notation".

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors