首页 > 解决方案 > 添加了地图图层。没有错误。图层不可见

问题描述

我使用以下代码生成地图图层:

var GeoJSON = {};
GeoJSON.type = "FeatureCollection";
GeoJSON.features = [];

var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        src: "~/icons/delivery-truck.png"
    }))
});

for (var i = 0; i < data.length; i++) {

    var machineGeoObject = {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": [data[i]["longitude"], data[i]["latitude"]],
        },
        "properties": data[i],
        "style": iconStyle
    }
    GeoJSON.features.push(machineGeoObject);
} //end of loop

var format = new ol.format.GeoJSON({
    featureProjection: "EPSG:3857"
});

var vector = new ol.layer.Vector({
    source: new ol.source.Vector({
       features: format.readFeatures(GeoJSON)
    })
});

map.addLayer(vector);

没有错误。当我map.getLayers()在控制台中调用时,我看到了添加的层。图层的属性“可见”为真。为什么我在地图上看不到带有图标的精确位置?为什么我只看到一张光秃秃的地图?

标签: openlayersopenlayers-5

解决方案


您可能在 OpenLayers 默认样式的大西洋中 lon/lat 0,0 的 180 米范围内可以看到特征。您不能通过 GeoJSON 设置 OpenLayers 样式,它必须设置在图层上,或者使用setStyle(). 此外featureProjection,该格式仅用于图层源设置,如果使用readFeatures必须在此处指定:

var GeoJSON = {};
GeoJSON.type = "FeatureCollection";
GeoJSON.features = [];

var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        src: "~/icons/delivery-truck.png"
    }))
});

for (var i = 0; i < data.length; i++) {

    var machineGeoObject = {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": [data[i]["longitude"], data[i]["latitude"]],
        },
        "properties": data[i],
    }
    GeoJSON.features.push(machineGeoObject);
} //end of loop

var format = new ol.format.GeoJSON();

var vector = new ol.layer.Vector({
    source: new ol.source.Vector({
       features: format.readFeatures(GeoJSON, {
         featureProjection: "EPSG:3857"
       })
    }),
    style: iconStyle
});

还要检查您的图标src网址是否正确(应该~...?)并确保data[i]["longitude"]data[i]["latitude"]是数字而不是字符串(Number()必要时使用)。


推荐阅读