001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
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.Main;
013import org.openstreetmap.josm.actions.ExtensionFileFilter;
014import org.openstreetmap.josm.data.projection.Projection;
015import org.openstreetmap.josm.gui.layer.Layer;
016import org.openstreetmap.josm.gui.layer.OsmDataLayer;
017import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
018import org.openstreetmap.josm.tools.Utils;
019
020public class GeoJSONExporter extends FileExporter {
021
022    protected final Projection projection;
023    public static final ExtensionFileFilter FILE_FILTER = new ExtensionFileFilter(
024            "geojson,json", "geojson", tr("GeoJSON Files") + " (*.geojson *.json)");
025    public static final ExtensionFileFilter FILE_FILTER_PROJECTED = new ExtensionFileFilter(
026            "proj.geojson", "proj.geojson", tr("Projected GeoJSON Files") + " (*.proj.geojson)");
027
028    /**
029     * A GeoJSON exporter which obtains the current map projection when exporting ({@link #exportData(File, Layer)}).
030     */
031    public static class CurrentProjection extends GeoJSONExporter {
032        public CurrentProjection() {
033            super(FILE_FILTER_PROJECTED, null);
034        }
035    }
036
037    /**
038     * Constructs a new {@code GeoJSONExporter} with WGS84 projection.
039     */
040    public GeoJSONExporter() {
041        this(FILE_FILTER, ProjectionPreference.wgs84.getProjection());
042    }
043
044    private GeoJSONExporter(ExtensionFileFilter fileFilter, Projection projection) {
045        super(fileFilter);
046        this.projection = projection;
047    }
048
049    @Override
050    public void exportData(File file, Layer layer) throws IOException {
051        if (layer instanceof OsmDataLayer) {
052            String json = new GeoJSONWriter((OsmDataLayer) layer, Utils.firstNonNull(projection, Main.getProjection())).write();
053            try (Writer out = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
054                out.write(json);
055            }
056        } else {
057            throw new IllegalArgumentException(tr("Layer ''{0}'' not supported", layer.getClass().toString()));
058        }
059    }
060}