You have to wait till features are loaded into the source, then you can get coordinates of the features. You can use vector source event featuresloadend
for that (see https://openlayers.org/en/latest/apidoc/module-ol_source_Vector-VectorSource.html and https://openlayers.org/en/latest/apidoc/module-ol_source_Vector.VectorSourceEvent.html).
Event featuresloadend
is fired when all the features are loaded into the source. Property evt.features
of event processing function parameter evt
contains all the loaded features. For this to work you have to add vector layer to the map.
Code could the look something like this:
function getCoordinatesOfCounties(evt) {
var features = evt.features;
features.forEach((feature) => {
var coordinates = feature.getGeometry().getCoordinates();
console.log(coordinates);
});
}
var vectorSource = new ol.source.Vector({
url: '/area.geojson',
format: new ol.format.GeoJSON()
});
vectorSource.on('featuresloadend', getCoordinatesOfCounties);
var vectorLayer = new ol.layer.Vector({
source: vectorSource;
});
map.addLyer(vectorLayer);
If you don't want to add layer to the map and just read features, you can use JS fetch
to read data and ol.format.GeoJSON().readFeatures
to read the features:
function getCoordinatesOfCounties(features) {
features.forEach((feature) => {
var coordinates = feature.getGeometry().getCoordinates();
console.log('coords', coordinates);
});
}
function readFeatures(data) {
var features = new ol.format.GeoJSON().readFeatures(data, {
dataProjection:'EPSG:4326',
featureProjection: 'EPSG:3857'
});
getCoordinatesOfCounties(features);
}
fetch('/area.geojson')
.then(response => response.json())
.then(data => {readFeatures(data)});
getCoordinatesOfCounties
function in the above code. When did you call it? It should be called afterfeaturesloadend
event is triggered on the vector source.