我试图通过坐标得到国家字符串,但是功能是空的。
为什么功能是空的?我怎么才能修好它?
我用onclick event.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"));
});发布于 2018-06-01 14:20:03
这是因为在调用postrender事件时,特性的加载还没有完成。您可以在vectorLayer上使用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:4326坐标,这需要转换为EPSG:3857 (默认情况下由OpenLayers使用)。
https://stackoverflow.com/questions/50640975
复制相似问题