1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.io.File;
|
---|
7 | import java.io.IOException;
|
---|
8 | import java.io.Writer;
|
---|
9 | import java.nio.charset.StandardCharsets;
|
---|
10 | import java.nio.file.Files;
|
---|
11 |
|
---|
12 | import org.openstreetmap.josm.Main;
|
---|
13 | import org.openstreetmap.josm.actions.ExtensionFileFilter;
|
---|
14 | import org.openstreetmap.josm.data.projection.Projection;
|
---|
15 | import org.openstreetmap.josm.gui.layer.Layer;
|
---|
16 | import org.openstreetmap.josm.gui.layer.OsmDataLayer;
|
---|
17 | import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
|
---|
18 | import org.openstreetmap.josm.tools.Utils;
|
---|
19 |
|
---|
20 | public class GeoJSONExporter extends FileExporter {
|
---|
21 |
|
---|
22 | protected final Projection projection;
|
---|
23 | public static final ExtensionFileFilter FILE_FILTER = new ExtensionFileFilter(
|
---|
24 | "geojson,json", "geojson", tr("GeoJSON Files") + " (*.geojson *.json)");
|
---|
25 | public static final ExtensionFileFilter FILE_FILTER_PROJECTED = new ExtensionFileFilter(
|
---|
26 | "proj.geojson", "proj.geojson", tr("Projected GeoJSON Files") + " (*.proj.geojson)");
|
---|
27 |
|
---|
28 | /**
|
---|
29 | * A GeoJSON exporter which obtains the current map projection when exporting ({@link #exportData(File, Layer)}).
|
---|
30 | */
|
---|
31 | public static class CurrentProjection extends GeoJSONExporter {
|
---|
32 | public CurrentProjection() {
|
---|
33 | super(FILE_FILTER_PROJECTED, null);
|
---|
34 | }
|
---|
35 | }
|
---|
36 |
|
---|
37 | /**
|
---|
38 | * Constructs a new {@code GeoJSONExporter} with WGS84 projection.
|
---|
39 | */
|
---|
40 | public GeoJSONExporter() {
|
---|
41 | this(FILE_FILTER, ProjectionPreference.wgs84.getProjection());
|
---|
42 | }
|
---|
43 |
|
---|
44 | private GeoJSONExporter(ExtensionFileFilter fileFilter, Projection projection) {
|
---|
45 | super(fileFilter);
|
---|
46 | this.projection = projection;
|
---|
47 | }
|
---|
48 |
|
---|
49 | @Override
|
---|
50 | public void exportData(File file, Layer layer) throws IOException {
|
---|
51 | if (layer instanceof OsmDataLayer) {
|
---|
52 | String json = new GeoJSONWriter((OsmDataLayer) layer, Utils.firstNonNull(projection, Main.getProjection())).write();
|
---|
53 | try (Writer out = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
|
---|
54 | out.write(json);
|
---|
55 | }
|
---|
56 | } else {
|
---|
57 | throw new IllegalArgumentException(tr("Layer ''{0}'' not supported", layer.getClass().toString()));
|
---|
58 | }
|
---|
59 | }
|
---|
60 | }
|
---|