[GIS] How to get the feature location in OpenLayers v3

javascriptopenlayers

After I am using the drawing interaction or modify interaction I have a listener that returns the feature that modified or added.

Example

draw.on('drawend', function (event) {
    // get the feature
    var feature = event.element;
    // ...listen for changes on it
    logStatus(feature.getId());
});

I know how to get the id, but I need the location (lon lat) of the feature because I need to save it to the DB, how can I do it? I didn't find it in the API.

Best Answer

If the features are points use

var coord = event.feature.getGeometry().getCoordinates();

For point geometries getCoordinates returns an array of 2 numbers. The first number is the x coordinate. The second number is the y coordinate.

And if you want to convert coord to a longitude and a latitude use:

coord = ol.proj.transform(coord, 'EPSG:3857', 'EPSG:4326');
var lon = coord[0];
var lat = coord[1];

The above assumes that your map view projection is Web Mercator (EPSG:3857), which is the default.