Javascript OpenLayer 3-GeoJSON-feature为空

Javascript OpenLayer 3-GeoJSON-feature为空,javascript,openlayers,openlayers-3,Javascript,Openlayers,Openlayers 3,我试图通过坐标获取国家字符串,但该特征为空 为什么特征为空?我怎样才能修好它 我使用onclick事件进行测试。pixel确实返回功能,但随后我使用映射。getPixelFromCoordinate获取pixel功能变为空 var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ url: 'https://openlayers.org/en/v4.6.5/examples/data/ge

我试图通过坐标获取国家字符串,但该特征为空

为什么特征为空?我怎样才能修好它

我使用onclick事件进行测试。pixel确实返回功能,但随后我使用映射。getPixelFromCoordinate获取pixel功能变为空

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"));
});

这是因为在调用
postdrender
事件时,功能加载尚未完成。您可以在
vectorLayer
上使用事件。如果函数更复杂,我建议使用
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:3857
(默认情况下由OpenLayers使用)的
EPSG:4326
坐标