[GIS] Trying to save Draw object in OpenLayers as GeoJSON with a different projection

geojsonopenlayers

I'm trying to draw a polygon or line then save that object into a database. The map is in EPSG:3857 projection but I would like to save the polygon as GeoJSON using EPSG:4326 projection.

I was hoping to use the dataProjection of the writeFeatureObject method but this still saves the data in EPSG:3857.

I did try transforming the geometry which worked for the output but then removes the polygon from the map as its in a different projection.

Below is some of my code:

draw.on("drawend", (arg1) => {
                console.log('Arg', arg1);
                // let rawGeo = arg1.feature.getGeometry();
                // let gps = rawGeo.transform('EPSG:3857', 'EPSG:4326');
                let parser = new ol.format.GeoJSON();
                let featuresGeoJSON = parser.writeFeatureObject(arg1.feature, {
                    dataProjection: 'EPSG:4326'
                });
                console.log(featuresGeoJSON)
            });

Hope you can point me in the right direction.

Best Answer

Ok well not sure how this happened as over the last two days i thought i had tried every variation, anyway i now have it working, the code is below.

draw.on("drawend", (arg1) => {
  let parser = new ol.format.GeoJSON();
  let area = parser.writeFeatureObject(arg1.feature, {featureProjection: 'EPSG:3857'});
});
Related Question