javascript - 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"));
});
解决方案
这是因为在postrender
调用事件时,功能的加载还没有完成。您可以使用postcompose
event 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 使用)。
推荐阅读
- python - 使用 Python 进行网页抓取:TypeError:“NoneType”类型的参数不可迭代
- payment-gateway - 无法调用基本回调万事达卡
- rest - 以正确的方式设计 REST-API
- spring-boot - 使用 Keycloak 的 Spring Boot 来保护休息服务
- hyperledger-fabric - 无法在 Fabric 中创建具有新组织的频道,出现错误:尝试包含不在联盟中的成员
- php - 在 Laravel 中显示来自搜索表单的多个结果的问题
- c++ - 当我的程序不在焦点时,不选择 GetAsyncKeyState。玩游戏时不工作
- python - 在 scipy.sparse 和 numpy 中处理不同的切片行为
- angular - 为什么我的 Angular 路由教程的后续代码显示空白页?
- ios - 如何使用自动布局调整 UILabel 宽度以适合文本?