[GIS] How to produce a GeoJSON with 1 point at a certain lon/lat

geojsongeotoolsjava

I need to create a GeoJSON string, which contains exactly one point at lon/lat 132.159633, 43.350116.

I'm trying to use GeoTools 12-RC1 for that.

Let's say I have following method, which is supposed to generate GeoJSON with that point:

public String geoData() {
    final GeometryBuilder builder = new GeometryBuilder();
    final Point point = builder.point(132.159633, 43.350116);
    return null; // Now I need to convert point to a GeoJSON string
}

How do I generate a GeoJSON string with point?

Best Answer

You need to import the GeoJSON plugn

<dependency>
  <groupId>org.geotools</groupId>
  <artifactId>gt-geojson</artifactId>
  <version>${geotools.version}</version>
</dependency>

and then call it like this (a full example is here):

public String geoData() {
    final GeometryBuilder builder = new GeometryBuilder();
    final Point point = builder.point(132.159633, 43.350116);
    SimpleFeatureBuilder fBuild = new SimpleFeatureBuilder(TYPE);
    fBuild.add(point);
    SimpleFeature feature = fBuild.buildFeature(null);
    FeatureJSON fjson = new FeatureJSON();
    StringWriter writer = new StringWriter();
    try {
        fjson.writeFeature(feature, writer);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String json = writer.toString();
    return json;
}