首页 > 解决方案 > OpenLayer 3 - GeoJSON - 功能为空

问题描述

我正在尝试通过坐标获取国家字符串,但功能为空。

为什么功能为空?我该如何解决?

我用 onclick event.pixel进行了测试,它确实返回了特征,但是我使用map.getPixelFromCoordinate来获取像素特征变为空

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: 'https://openlayers.org/en/v4.6.5/examples/data/geojson/countries.geojson',
        format: new ol.format.GeoJSON()
    })
});

var map = new ol.Map({
    layers: [ vectorLayer],
    target: 'map',
    view: new ol.View({
        center: [0, 0],
        zoom: 1
    }),
    logo:false
  });

这不起作用

map.once('postrender', function() {
    var pixel = map.getPixelFromCoordinate([-0.0508, 51.5160]);

    var feature = map.forEachFeatureAtPixel(pixel, function(feature) { 
        return feature;
    });

    console.log("Country:"+feature.get("name"));
});

标签: javascriptopenlayersopenlayers-3

解决方案


这是因为在postrender调用事件时,功能的加载还没有完成。您可以使用postcomposeevent onvectorLayer代替。如果函数会更复杂,我建议使用ol.source.Vector加载器函数。

vectorLayer.on('postcompose', function () {
    var pixel = map.getPixelFromCoordinate(ol.proj.fromLonLat([-0.0508, 51.5160]));
    var feature = map.forEachFeatureAtPixel(pixel, function (feature) {
        return feature;
    });
    console.log("Country:"+feature.get("name"));
});

此外,您似乎正在传递EPSG:4326需要转换的坐标EPSG:3857(默认情况下由 OpenLayers 使用)。


推荐阅读