I have a map with a simple GeoJSON file layer (several towns) which has a 'bbox' property for each town. It is a point or a linestring. The GeoJSON file looks like this:
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Rome","bbox":"12.486137, 41.891775, 12.487089, 41.891481"},"geometry":{"type":"Point","coordinates":[12.486137,41.891775]}}]}
Everything is fine when I use the usual way to add a GeoJSON file as Vector Layer. But how can I add a geometry from 'bbox' property of the file as a different layer? Should I add some brackets and commas?
I tried something like this but it didn't add anything:
const styleBBox = new Style({
fill: new Fill(),
stroke: new Stroke({
color: '#000',
width: 1,
})
});
const BBox = new VectorLayer({
source: new VectorSource(),
style: function (feature) {
const coordinates = feature.get('bbox');
styleBBox.getGeometry().getCoordinates(coordinates);
return styleBBox;
},
});
You will need to specify geometry
in the style if you need to display a different geometry to the feature's own geometry. You can convert a bbox to a polygon geometry using fromExtent
https://openlayers.org/en/latest/apidoc/module-ol_geom_Polygon.html#.fromExtent
const BBox = new VectorLayer({
source: new VectorSource(),
style: new Style({
geometry: function(feature) {
return fromExtent(
feature.get('bbox').split(',').map(Number)
).transform('EPSG:4326', map.getView().getProjection());
},
stroke: new Stroke({
width: 2,
color: 'black'
}),
}),
});
Note that your bbox coordinates are non-standard and may be rejected - they should represent the SW and NE corners https://datatracker.ietf.org/doc/html/rfc7946#section-5