LoginSignup
10
15

More than 5 years have passed since last update.

ShapeファイルをGeoJSONに変換する。

Last updated at Posted at 2015-11-08

MashupAwards11向けに神戸アルクマップというWebサービスを作る際、国土数値情報等の大量のShapeファイルをElasticsearchに入れる必要があった。
このため、ShapeファイルをGeoJSONに変換するプログラムを書いたので、メモしておく。
ファイル変換にはGeoToolsを使用しています。

せっかくなので、HerokuにShp2JSONというWebサービスを構築してみました。
Shp2JSON

Shape2GeoJSON.java
package modules;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;

import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;

public class Shape2GeoJSON {

    public static String getJSON(File f,String encoding)throws Exception{
        f.setReadOnly();
        ShapefileDataStore store = new ShapefileDataStore(f.toURI().toURL());
        Charset cs=Charset.forName(encoding);
        store.setCharset(cs);
        SimpleFeatureSource source = store.getFeatureSource();
        SimpleFeatureCollection featureCollection = source.getFeatures();
        String geoJson=null;
        FeatureJSON fj = new FeatureJSON();
        StringWriter writer = new StringWriter();
        fj.writeFeatureCollection(featureCollection, writer);
        geoJson = writer.toString();
        return geoJson;
    }

    public static File getGeoJSON(String json,String path,String encoding) throws Exception{
        File out=new File(path);
        PrintWriter pw=null;
        try{
            FileOutputStream fos = new FileOutputStream(out);
            OutputStreamWriter osw = new OutputStreamWriter(fos,encoding);
            pw = new PrintWriter(osw);
            pw.write(json);
            pw.close();
            pw=null;
            return out;
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(pw!=null){
                pw.close();
            }
        }
        return null;
    }

}

10
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
15