首页 > 解决方案 > 如何从 GeoJSON 数据中设置自定义标记图标

问题描述

我收到来自服务器的 GeoJSON 格式的响应,并将其全部添加到地图中

$.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');
        }
    }); 

代码功能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'});
    }
}

我不知道如何根据对象编号更改图标。感谢帮助!

标签: javascriptleaflet

解决方案


您必须将图标直接添加到标记:

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

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

推荐阅读