json生成shp_解析shp文件生成geojson格式数据

package cn.ssk.geotools;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.net.URL;

import java.util.HashMap;

import org.geotools.data.FileDataStoreFinder;

import org.geotools.data.shapefile.ShapefileDataStore;

import org.geotools.data.simple.SimpleFeatureCollection;

import org.geotools.data.simple.SimpleFeatureIterator;

import org.geotools.data.simple.SimpleFeatureSource;

import org.geotools.factory.GeoTools;

import org.opengis.feature.simple.SimpleFeature;

import cn.ssk.mysql.AreaInfo;

import cn.ssk.mysql.MysqlUtils;

import sun.nio.cs.ext.GBK;

public class GeotoolDemo {

private static HashMap codeMap=MysqlUtils.getCodeMap();

private static HashMap jsonFiles=new HashMap<>();

public static void main(String[] args)throws Exception {

URL url=GeoTools.class.getClassLoader().getResource("xian.shp");

File file=new File(url.toURI());

handleProcess(file);

}

public static void handleProcess(File shpfile)throws Exception{

ShapefileDataStore fdstore=(ShapefileDataStore)FileDataStoreFinder.getDataStore(shpfile);

fdstore.setCharset(new GBK());

SimpleFeatureSource source=fdstore.getFeatureSource();

SimpleFeatureCollection sfc=source.getFeatures();

try(SimpleFeatureIterator iterator=sfc.features()){

AreaInfo info;

while(iterator.hasNext()){

SimpleFeature feature=iterator.next();

String cityName=feature.getAttribute("NAME").toString();

String polygon=feature.getAttribute("the_geom").toString();

info=codeMap.get(cityName);

if(info!=null){

Integer mgr=info.getMgr();

String coordinates=parseCoordinate(polygon);

if(jsonFiles.containsKey(mgr.toString())){

FileWriter fw=jsonFiles.get(mgr.toString());

fw.append(",");

appendToFile(fw,coordinates,cityName);

}else{

FileWriter fw=new FileWriter(mgr.toString()+".json",true);

fw.append("{\"type\":\"FeatureCollection\",\"features\":[");

fw.flush();

jsonFiles.put(mgr.toString(), fw);

appendToFile(fw, coordinates,cityName);

}

}

}

for(String filename :jsonFiles.keySet()){

FileWriter writer=jsonFiles.get(filename);

writer.append("]}");

writer.flush();

writer.close();

}

}

}

public static void appendToFile(FileWriter writer,String coordinate,String cityName) throws IOException{

writer.append("{\"type\":\"Feature\",\"properties\":{\"name\":\"");

writer.append(cityName);

writer.append("\"},");

writer.append("\"geometry\":{\"type\":\"MultiPolygon\",\"coordinates\":");

writer.append(coordinate);

writer.append("}}");

writer.flush();

}

private static String geojsonWrapper(String polygon){

StringBuilder sber=new StringBuilder(polygon.length()+30);

String tmp[]=polygon.split(",");

sber.append("[[[");

for(int i=0;i

sber.append("[");

sber.append(tmp[i].trim().replace(" ", ","));

sber.append("]");

if(i != tmp.length-1)

sber.append(",");

}

sber.append("]]]");

return sber.toString();

}

public static String parseCoordinate(String polygon){

int beginIndex=polygon.indexOf("(((")+3;

int endIndex=polygon.lastIndexOf(")))");

String s=polygon.substring(beginIndex,endIndex).replace('(', ' ').replace(')', ' ');

return geojsonWrapper(s);

}

}

根据县的名称,查询县所属的市,该关系存入一个数据库表中,也可存入文件中。

package cn.ssk.mysql;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.HashMap;

public class MysqlUtils {

private static final String driver="com.mysql.jdbc.Driver";

private static final String url="jdbc:mysql://localhost:3306/geotools";

private static final String username="root";

private static final String password="123456";

private static Connection conn=null;

private static PreparedStatement stmt=null;

private static ResultSet rs=null;

private static HashMap codeMap=new HashMap<>();

static{

try {

Class.forName(driver);

conn=DriverManager.getConnection(url, username, password);

init();

} catch (Exception e) {

throw new RuntimeException(e);

}

}

public static void close(ResultSet rs,PreparedStatement stmt,Connection conn){

try {

if(rs!=null){rs.close();}

if(stmt!=null){stmt.close();}

if(conn!=null){conn.close();}

} catch (Exception e) {

throw new RuntimeException(e);

}

}

private static void init(){

AreaInfo info; //数据库表对应bean

try {

stmt=conn.prepareStatement("select code,cityName,mgr from areacode where code like ?");

stmt.setString(1, "15____");//根据省份编号仅获取该省县市的编码对应关系

rs=stmt.executeQuery();

while(rs.next()){

info=new AreaInfo();

info.setCode(rs.getInt("code"));

info.setCityName(rs.getString("cityName"));

info.setMgr(rs.getInt("mgr"));

codeMap.put(rs.getString("cityName"), info);

}

} catch (SQLException e) {

throw new RuntimeException(e);

}finally {

close(rs,stmt,conn);

}

}

public static HashMap getCodeMap() {

return codeMap;

}

}

数据库行政区划代码关系表(数据来自国家统计局最新数据):

code:县或市的行政区划代码,mgr 县所属的市的代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 GeoTools 库来实现将 SHP 文件发布为 GeoJSON 格式的服务。下面是一个示例代码: ```java import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CoverageStoreInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.StoreInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.impl.CatalogImpl; import org.geoserver.data.util.IOUtils; import org.geoserver.platform.GeoServerExtensions; import org.geoserver.wfs.WFSServiceImpl; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.FeatureSource; import org.geotools.data.FeatureStore; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.feature.FeatureCollection; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.geometry.jts.ReferencedEnvelope; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.filter.Filter; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/geojson") public class GeoJSONController { private Catalog catalog; public GeoJSONController() { this.catalog = new CatalogImpl(); } @RequestMapping(value = "/{workspace}/{datastore}/{layer}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> getGeoJSON(@PathVariable("workspace") String workspaceName, @PathVariable("datastore") String datastoreName, @PathVariable("layer") String layerName, HttpServletRequest request) { try { WorkspaceInfo workspace = catalog.getWorkspaceByName(workspaceName); DataStoreInfo dataStore = catalog.getDataStoreByName(datastoreName, workspace); FeatureTypeInfo featureType = catalog.getFeatureTypeByName(workspaceName, layerName); DataStore datastore = DataStoreFinder.getDataStore(dataStore.getConnectionParameters()); SimpleFeatureSource featureSource = datastore.getFeatureSource(featureType.getName()); FeatureCollection<SimpleFeatureType, SimpleFeature> collection = featureSource.getFeatures(); SimpleFeatureCollection features = (SimpleFeatureCollection) collection; // Convert SimpleFeatureCollection to GeoJSON FeatureJSON featureJSON = new FeatureJSON(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); featureJSON.writeFeatureCollection(features, outputStream); return ResponseEntity.ok(outputStream.toString()); } catch (Exception e) { return ResponseEntity.status(500).body("Error: " + e.getMessage()); } } } ``` 在此代码中,我们首先获取了指定的工作空间、数据存储和要素类型。然后,我们使用 `DataStoreFinder` 类创建一个 `DataStore` 实例,并从中获取要素源。接下来,我们使用 GeoTools 库的 `FeatureJSON` 类将 `SimpleFeatureCollection` 换为 GeoJSON 字符串,并返回该字符串作为响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值