Shp、Xls、Geojson三者之间相互转化的核心代码

本文介绍如何使用Java实现SHP文件与GeoJSON文件之间的相互转换,并提供了一个示例,展示如何将Excel文件转换为SHP文件。

当我们在使用的的的的OpenLayers的时候,我们需要有需要以以以GeoJSON的的数据。但是我们手里只有.SHP的文件。此时我们很苦恼,现在我来拯救你来了。

** 
     * shp转换为Geojson 
     * @param shpPath 
     * @return 
     */  
    public Map shape2Geojson(String shpPath, String jsonPath){  
        Map map = new HashMap();  
          
        FeatureJSON fjson = new FeatureJSON();  
          
        try{  
            StringBuffer sb = new StringBuffer();  
            sb.append("{\"type\": \"FeatureCollection\",\"features\": ");  
              
            File file = new File(shpPath);  
            ShapefileDataStore shpDataStore = null;  
              
            shpDataStore = new ShapefileDataStore(file.toURL());  
            //设置编码  
            Charset charset = Charset.forName("GBK");  
            shpDataStore.setStringCharset(charset);  
            String typeName = shpDataStore.getTypeNames()[0];  
            SimpleFeatureSource featureSource = null;  
            featureSource =  shpDataStore.getFeatureSource (typeName);  
            SimpleFeatureCollection result = featureSource.getFeatures();  
            SimpleFeatureIterator itertor = result.features();  
            JSONArray array = new JSONArray();  
            while (itertor.hasNext())  
            {  
                SimpleFeature feature = itertor.next();  
                StringWriter writer = new StringWriter();  
                fjson.writeFeature(feature, writer);  
                JSONObject json = new JSONObject(writer.toString());  
                array.put(json);  
                
            }  
            itertor.close();  
            sb.append(array.toString());  
            sb.append("}");  
              
            //写入文件  
            cm.append2File(jsonPath, sb.toString());  
              
            map.put("status", "success");  
            map.put("message", sb.toString());  
        }  
        catch(Exception e){  
            map.put("status", "failure");  
            map.put("message", e.getMessage());  
            e.printStackTrace();  
              
        }  
        return map;  
    }  

有时,我们在需要的.SHP文件的时候,此时手里面又只有以GeoJSON的的的的文件。此时我这里又派上作用了。

/** 
     * geojson转换为shp文件 
     * @param jsonPath 
     * @param shpPath 
     * @return 
     */  
    public Map geojson2Shape(String jsonPath, String shpPath){  
        Map map = new HashMap();  
        GeometryJSON gjson = new GeometryJSON();  
      
        try{ 
       
        String strJson = cm.getFileContent(jsonPath);  
            JSONObject json = new JSONObject(strJson);  
            JSONArray features = (JSONArray) json.get("features");  
            JSONObject feature0 = new JSONObject(features.get(0).toString());  
            System.out.println(feature0.toString());  
            String strType = ((JSONObject)feature0.get("geometry")).getString("type").toString();  
              
            Class<?> geoType = null;  
            switch(strType){  
                case "Point":  
                    geoType = Point.class;  
                case "MultiPoint":  
                    geoType = MultiPoint.class;  
                case "LineString":  
                    geoType = LineString.class;  
                case "MultiLineString":  
                    geoType = MultiLineString.class;  
                case "Polygon":  
                    geoType = Polygon.class;  
                case "MultiPolygon":  
                    geoType = MultiPolygon.class;  
            }  
            //创建shape文件对象  
            File file = new File(shpPath);  
            Map<String, Serializable> params = new HashMap<String, Serializable>();  
            params.put( ShapefileDataStoreFactory.URLP.key, file.toURI().toURL() );  
            ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);  
            //定义图形信息和属性信息  
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();  
            tb.setCRS(DefaultGeographicCRS.WGS84);  
            tb.setName("shapefile");  
            tb.add("the_geom", geoType);  
            tb.add("POIID", Long.class);  
            ds.createSchema(tb.buildFeatureType());  
            //设置编码  
            Charset charset = Charset.forName("GBK");  
            ds.setStringCharset(charset);  
            //设置Writer  
            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);  
              
            
            for(int i=0,len=features.length();i<len;i++){  
                String strFeature = features.get(i).toString();  
                Reader reader = new StringReader(strFeature);  
                SimpleFeature feature = writer.next(); 
                //这里看geojson是什么类型的。这里的readMultiLine才知道是什么的样的。否则会出现错误。
                feature.setAttribute("the_geom",gjson.readMultiLine(reader));
//                Object readMulti = null;
//                switch(strType){  
//                case "Point":  
//                readMulti=gjson.readPoint(reader);
//                case "MultiPoint":  
//                readMulti=gjson.readMultiPoint(reader);
//                case "LineString":  
//                readMulti=gjson.readLine(reader);
//                case "MultiLineString":  
//                  readMulti=gjson.readMultiLine(reader);
//                case "Polygon":  
//                   readMulti=gjson.readPolygon(reader);
//                case "MultiPolygon":  
//                   readMulti=gjson.readMultiPolygon(reader);
//            } 
//              
//                feature.setAttribute("the_geom",readMulti);
                feature.setAttribute("POIID",i);  
                writer.write();  
            }  
            writer.close();  
            ds.dispose();  
            map.put("status", "success");  
            map.put("message", shpPath);  
        }  
        catch(Exception e){  
            map.put("status", "failure");  
            map.put("message", e.getMessage());  
            e.printStackTrace();  
        }  
        return map;  
    }  

是不是看上去很简单,是的就是这么简单。下面让我们来看下我们的CSV文件如何转化的吧的的的的.csv文件可以是甲骨文的MySQL的的的或者导出的文件。此时如果你从数据库中导出了CSV文件,但是又想把它生存的.SHP文件。此时这里的代码是不是又解了你的燃眉之急呢?不说了,直接上代码。

/**
    * excel转shp 
    * @param xlsfile
    * @param shppath
    */
    public void excel2Shape(String xlsfile, String shppath) {  
        POIFSFileSystem fs;  
        HSSFWorkbook wb;  
        HSSFRow row;  
        try {  
            InputStream is = new FileInputStream(xlsfile);  
            fs = new POIFSFileSystem(is);  
            wb = new HSSFWorkbook(fs);  
            sheet = wb.getSheetAt(0);  
            //获取总列数  
            int colNum = sheet.getRow(0).getPhysicalNumberOfCells();  
            // 得到总行数  
            int rowNum = sheet.getLastRowNum();  
  
            List list = getExcelHeader();  
            //创建shape文件对象  
            File file = new File(shppath);  
            Map<String, Serializable> params = new HashMap<String, Serializable>();  
            params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());  
            ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);  
            //定义图形信息和属性信息  
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();  
            tb.setCRS(DefaultGeographicCRS.WGS84);  
            tb.setName("shapefile");  
            tb.add("the_geom", Point.class);  
            for (int i = 0; i < list.size(); i++) {  
                Map<String, Object> map = (Map<String, Object>) list.get(i);  
                tb.add(map.get("name").toString(), (Class) map.get("type"));  
            }  
            ds.createSchema(tb.buildFeatureType());  
            //设置编码  
            Charset charset = Charset.forName("GBK");  
            ds.setStringCharset(charset);  
            //设置Writer  
            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);  
            //写下一条  
            SimpleFeature feature = null;  
            for (int i = 1; i < rowNum; i++) {  
                row = sheet.getRow(i);  
                feature = writer.next();  
                Map mapLonLat = new HashMap();  
                for (int j = 0; j < colNum; j++) {  
                    HSSFCell cell = row.getCell(j);  
                    Map<String, Object> mapFields = (Map<String, Object>) list.get(j);  
                    String fieldName = mapFields.get("name").toString();  
                    feature.setAttribute(fieldName, getCellValue(cell));  
                    if (fieldName.toLowerCase().equals("lon") || fieldName.toLowerCase().equals("lat")) {  
                        mapLonLat.put(fieldName, getCellValue(cell));  
                    }  
                }  
                feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate((double) mapLonLat.get("lon"), (double) mapLonLat.get("lat"))));  
            }  
            writer.write();  
            writer.close();  
            ds.dispose();  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

是不是很简单。我知道你们有的会问,上面的那个getFirstHeadWordChar()方法里面是什么是吧。我都猜到了。

/**
     * 提取第一个汉子/单词的首字母(大写)
     * 
     * @param str
     * @return
     */
    public static String getFirstHeadWordChar(String str) {
        if (isNull(str)) {
            return "";
        }
        String convert = "";
        char word = str.charAt(0);
        // 提取汉字的首字母
        String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
        if (pinyinArray != null) {
            convert += pinyinArray[0].charAt(0);
        }
        else {
            convert += word;
        }




        convert = string2AllTrim(convert);
        return convert.toUpperCase();
    }




/**
     * 提取每个汉字的首字母(大写)
     * 
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {
        if (isNull(str)) {
            return "";
        }
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            // 提取汉字的首字母
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            }
            else {
                convert += word;
            }
        }




        convert = string2AllTrim(convert);
        return convert.toUpperCase();
    }




    /*
     * 判断字符串是否为空
     */




    public static boolean isNull(Object strData) {
        if (strData == null || String.valueOf(strData).trim().equals("")) {
            return true;
        }
        return false;
    }




    /**
     * 去掉字符串包含的所有空格
     * 
     * @param value
     * @return
     */
    public static String string2AllTrim(String value) {
        if (isNull(value)) {
            return "";
        }
        return value.trim().replace(" ", "");
    }

是不是很简单。上面是我写的一个工具类。哦,好像还掉了一点。上面还有一个文件写入的代码append2File()和一个文件读取的方法getFileContent()。

/**
     * 文件写入
     * @param jsonPath
     * @param soure
     */
public void append2File(String jsonPath, String soure) {
// TODO Auto-generated method stub
File file = new File(jsonPath);


        try {
            OutputStream os = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(os);
            osw.write(soure);
            osw.flush();
            osw.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}


/*
* 文件读取
* */
public String getFileContent(String jsonPath) {
File file = new File(jsonPath);
StringBuffer sb=new StringBuffer();
       try {
       InputStream out = new FileInputStream(file);
       InputStreamReader reader=new InputStreamReader(out,"GBK");
       while (reader.ready()) {
sb.append((char)reader.read());
}
       
       out.close();
  reader.close();
} catch (Exception e) {
// TODO: handle exception
}
return sb.toString();
}

现在我们做GIS的项目。希望这些能帮助到一些人吧。后期我会更新一些有关openlayer的一些知识,感觉GIS还是蛮好玩。

再见了大家。拜拜

备注源码下载地址:https://download.youkuaiyun.com/download/yuwinter/10311544

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuwinter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值