[GIS] How to extract GeoJSON vector layer coordinates from DOM, Openlayers 3

geojsonjqueryopenlayers

I created a GeoJSON vector layer using OpenLayers 3 API, the vector layer is a county map. My goal is by clicking, I will be able to select the county and extract the coordinates. (like shown below)
enter image description here

My current method of extracting the coordinates is once on.select, goes to the DOM and find the coordinates. Something like this:

var coords;
var select = new ol.interaction.Select();
    map.addInteraction(select);

// var selectedFeature = select.getFeatures();
selectclick = select;
selectclick.on('select', function(e)
{
  if (e!== null)
  {
  console.log(e),
  coords = e.selected[0].c.target.s;
  console.log(coords);
  }
});

This way works find, but I had to manually go the DOM and find the coordinates myself, then write the location in variable "coords". This probably not a good solution when face dynamic environments. Is there a better way to find coordinates in my case?

Best Answer

You can access source of your layer then access features of the source and coordinates of features with getCoordinates() method of ol.geom.Polygon. Try like this:

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: '/your_counties.geojson',
        format: new ol.format.GeoJSON()
    })
});

//call this whereever you want from
function getCoordinatesOfCounties() {
    var features = vectorLayer.getSource().getFeatures();
    features.forEach((feature) => {
        console.log(feature.getCoordinates());
    });
}
Related Question