001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.io.importexport;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.File;
007import java.io.IOException;
008import java.io.Writer;
009import java.nio.charset.StandardCharsets;
010import java.nio.file.Files;
011
012import org.openstreetmap.josm.actions.ExtensionFileFilter;
013import org.openstreetmap.josm.gui.layer.Layer;
014import org.openstreetmap.josm.gui.layer.OsmDataLayer;
015import org.openstreetmap.josm.io.GeoJSONWriter;
016
017/**
018 * Exporter to write map data to a GeoJSON file.
019 * @since 4886
020 */
021public class GeoJSONExporter extends FileExporter {
022
023    /** File extension filter for .geojson files */
024    public static final ExtensionFileFilter FILE_FILTER = new ExtensionFileFilter(
025            "geojson,json", "geojson", tr("GeoJSON Files") + " (*.geojson *.json)");
026
027    /**
028     * Constructs a new {@code GeoJSONExporter} with WGS84 projection.
029     */
030    public GeoJSONExporter() {
031        super(FILE_FILTER);
032    }
033
034    @Override
035    public void exportData(File file, Layer layer) throws IOException {
036        if (layer instanceof OsmDataLayer) {
037            try (Writer out = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
038                out.write(new GeoJSONWriter(((OsmDataLayer) layer).data).write());
039            }
040        } else {
041            throw new IllegalArgumentException(tr("Layer ''{0}'' not supported", layer.getClass().toString()));
042        }
043    }
044}