1

How can I get drawn features in Openlayers 4 in TopoJSON format. I can get the features in GeoJSON as shown in below snippet

.................................
var draw = new ol.interaction.Draw({
  source: source,
  type: 'Polygon'
});
map.addInteraction(draw);
.................................
function getDrawnFeatures(){
  var format = new ol.format.GeoJSON();
  /* var format = new ol.format.TopoJSON(); */
  /* below line gives me "Uncaught TypeError: format.writeFeatures is not a function" if i use var format = new ol.format.TopoJSON(); */
  return format.writeFeatures(source.getFeatures()); 
}

I cannot find find writeFeatures function in ol.format.TopoJSON from the docs.

1

There are no writeFeatures for TopoJSON reading the API http://openlayers.org/en/latest/apidoc/ol.format.TopoJSON.html

You can use the official library https://github.com/topojson/topojson loaded in a script tag <script src="https://unpkg.com/topojson@3"></script>

For the demo, we consider you are loading an existing source vectorSource and an associated vector layer (You will find an associated demo, tested)

vectorSource.on('change', evt => {
  if (vectorSource.getState() === 'ready') {
    var geojsonObject = (new ol.format.GeoJSON())
      .writeFeaturesObject(
        vectorSource.getFeatures(), {
          featureProjection: 'EPSG:3857'
        }
      );
    console.log('GeoJSON', geojsonObject);
    var topojsonObject = topojson.topology({
      world: geojsonObject
    });
    console.log('TopoJSON', topojsonObject);
  }
})
  • This works perfectly. One more thing; TopoJSON is suposed to be lighter than GeoJSON. But the topojson created by converting the geojson data in the above example is larger than geojson data. (at least in the size of bytes.). Any Idea about that,? – Johnson Jun 14 '18 at 7:21
  • When I do a JSON.stringify of both, 285 569 characters for TopoJSON, 350 978 for GeoJSON. So not sure how you get the opposite – ThomasG77 Jun 14 '18 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.