Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Java Object in to GeoJSON (Required by d3 Graph) [closed]

I want to convert java List object into D3 GeoJSON. Is there any java api available that help to convert java object to GeoJSON object. I want to display graph in d3. Can anyone help me to solve this problem?

like image 889
Milople Inc Avatar asked Dec 08 '22 12:12

Milople Inc


1 Answers

GeoJSON is very simple; a general JSON library should be all you need. Here's how you could construct a list of Points using the json.org code (http://json.org/java/):

    JSONObject featureCollection = new JSONObject();
    try {
        featureCollection.put("type", "featureCollection");
        JSONArray featureList = new JSONArray();
        // iterate through your list
        for (ListElement obj : list) {
            // {"geometry": {"type": "Point", "coordinates": [-94.149, 36.33]}
            JSONObject point = new JSONObject();
            point.put("type", "Point");
            // construct a JSONArray from a string; can also use an array or list
            JSONArray coord = new JSONArray("["+obj.getLon()+","+obj.getLat()+"]");
            point.put("coordinates", coord);
            JSONObject feature = new JSONObject();
            feature.put("geometry", point);
            featureList.put(feature);
            featureCollection.put("features", featureList);
        }
    } catch (JSONException e) {
        Log.error("can't save json object: "+e.toString());
    }
    // output the result
    System.out.println("featureCollection="+featureCollection.toString());

This will output something like this:

{
"features": [
    {
        "geometry": {
            "coordinates": [
                -94.149, 
                36.33
            ], 
            "type": "Point"
        }
    }
], 
"type": "featureCollection"
}
like image 76
kielni Avatar answered Dec 11 '22 11:12

kielni