简体   繁体   中英

How to set custom marker icons from GeoJSON data

I receive a response from the server in GeoJSON format and add this all to the map

$.ajax({
        url: '/coupling/select/',
        type: 'post',
        data: {
            sw_lat: southWest.lat,
            sw_lon: southWest.lng,
            ne_lat: northEast.lat,
            ne_lon: northEast.lng
        },
        success: function (data) {
            L.geoJSON(data, {
                icon: leafletIcon, 
                onEachFeature: onEachFeature
            }).addTo(map)
        },
        complete: function () {
            loader_countdown_dec('coupling');
        }
    }); 

Code function leafletIcon:

function leafletIcon(feature){
    if(feature.properties.obj == 1){
        return L.icon({iconUrl: 'images/cable.png'});
    }
    else if(feature.properties.obj == 2){
        return L.icon({iconUrl: 'images/boxpon.png'});
    }
    else if(feature.properties.obj == 3){
        return L.icon({iconUrl: 'images/coupling.png'});
    }
}

I can't figure out how to change the icon depending on the object number. Thanks for help!

You have to add the icon directly to the marker:

 L.geoJSON(data, {
                pointToLayer: pointToLayer, 
                onEachFeature: onEachFeature
            }).addTo(map)

function pointToLayer(feature, latlng) {
    return L.marker(latlng, {icon: leafletIcon(feature)});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM