OpenLayer 3 - GeoJSON - feature is null



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

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

我使用 onclickevent.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"));
});

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

最新更新