简体   繁体   中英

Converting OpenLayers Polygon to GeoJSON with different projection

Similar to the problem found in this question

How to convert OpenLayers polygon coordinates into latitude and longitude?

I have setup a basic map to capture a user defined polygon and convert it to GeoJSON, whilst I'm able to do this with its native projection (ESPG:3857) I would like to take the captured GeoJSON and convert it to EPSG:4326 - which I will then save away. Using the above method of capturing the feature on the drawend event and performing a transform however removes the polygon as the new co-ordinates are not represented in the projection of the map any longer. I am unable to figure out how to to save the GeoJSON in the format I need without deleting the existing polygon

I have tried performing this by using getFeatures on the vector source of the polygon and then performing a transform from the projection i'm using to the projection I want, but this still returns the same coords, I have also (like the linked article) tried using the the writeFeatureObject but it still saves incorrectly

https://jsfiddle.net/20gxo3nt/


dragBox.on('drawend', function(evt){

/*   geom = evt.feature.getGeometry().transform('EPSG:3857', 'EPSG:4326');
  console.log(geom.getCoordinates()); */

});

$( "#save" ).click(function() {
  var geom=vectorSource.getFeatures();
  console.log(geom);
  var writer=new ol.format.GeoJSON();
  var geoJsonStr = writer.writeFeatures(geom);
  console.log (geom.proj.transform('EPSG:3857', 'EPSG:4326'));
  /* console.log(geoJsonStr) */
});

Uncommenting the code on the drawend event will correctly console.log the co-ordinates,as well as demonstrate polygon disappearing

To get a new geojson

  var geom = [];
  vectorSource.forEachFeature( function(feature) { geom.push(new ol.Feature(feature.getGeometry().clone().transform('EPSG:3857', 'EPSG:4326'))); } );
  var writer = new ol.format.GeoJSON();
  var geoJsonStr = writer.writeFeatures(geom);
   console.log(geoJsonStr);

Openlayers 6 , no need to loop on features

var format = new ol.format["GeoJSON"](); 
var geoJsonStr = format.writeFeatures(vectorSource.getFeatures(), { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM