I faced the following problem: I compiled a usefull map with own generated geojson data, that's work fine. Now I want to make summary box next to the map, the data for summary text is from the same geojson file with specific id (and fictitious coords) to reach them. So, I try to reach them with "getFeatureById", but it throws null...
Snippet from the geojson file (the first paragraph is data for summary text, the next paragraph is conventional geojson data):
{ "type": "FeatureCollection", "features": [
{"type": "Feature", "geometry": { "type": "Point", "coordinates": [0,0] }, "properties": { "id":"node/BP", "ossz_tervkoltseg":"9045.1", ... } },
{"type": "Feature", "geometry": { "type": "Point", "coordinates": [19.0908557,47.5269017] }, "properties": { "id":"node/8420278688", "ossz_tervkoltseg":"370.5", ... } },
...
My script:
const map = new ol.Map({
view: new ol.View({ center: [2164846.200859313,5963803.432942492], zoom: 7.5}),
layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ],
target: 'js-map' });
const prbGeoJSON = new ol.layer.VectorImage({
source: new ol.source.Vector({ url: "./mli.geojson", format: new ol.format.GeoJSON() }),
visible: true,
title: "prbGeoJSON",
style: function(feature, resolution){ ... } });
map.addLayer(prbGeoJSON); // it works fine so far
map.once('postrender', function(event) {
let feature = prbGeoJSON.getSource().getFeatureById("node/BP");
console.log(feature); // throw null...
});
What have I done wrong?
The id should appear direcly in the feature object, not in its properties object
{"type": "Feature", "geometry": { "type": "Point", "coordinates": [0,0] }, "id": "node/BP", "properties": { "ossz_tervkoltseg":"9045.1", ... } },
If you need to use something from the properties object as a unique id for lookups you could set it when the features are added to the source
prbGeoJSON.getSource().on('addfeature', function(event) (
event.feature.setId(event.feature.get('id');
});