I'm trying to extract coordinates from a GeoJSON file . I tried this line of code but I didn't have result in the console.
<script type="text/javascript">
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '/area.geojson',
format: new ol.format.GeoJSON()
})
});
function getCoordinatesOfCounties() {
var features = vectorLayer.getSource().getFeatures();
features.forEach((feature) => {
var coordinates = feature.getGeometry().getCoordinates();
console.log(coordinates);
});
}
</script>
What's wrong?
1 Answer 1
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)});
-
I'm sorry but even when I tried this , I didn't have a result on the console !@TomazicMAhmed– Ahmed2021年09月23日 10:19:52 +00:00Commented Sep 23, 2021 at 10:19
-
You have to add vector layer to the map for the features to be loaded into the source.TomazicM– TomazicM2021年09月23日 10:22:17 +00:00Commented Sep 23, 2021 at 10:22
-
See modified answer.TomazicM– TomazicM2021年09月23日 10:45:02 +00:00Commented Sep 23, 2021 at 10:45
getCoordinatesOfCounties
function in the above code. When did you call it? It should be called afterfeaturesloadend
event is triggered on the vector source.