引入geotools依赖:
<!-- geotools主要依赖 -->
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-metadata</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-referencing</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-wkt</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-data</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>javax.measure</groupId>
<artifactId>jsr-275</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-api</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-main</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-jdbc</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools.jdbc</groupId>
<artifactId>gt-jdbc-postgis</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-opengis</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>2.7.2</version>
</dependency>
功能实现代码:
@Service
public class LayerService {
@Resource
private GeoserverDao geoserverDao;
@Resource
private GeoServer geoServer;
@Transactional
public void addLayer(String filePath) throws Exception{
File dir = new File(filePath);
File[] subFiles = dir.listFiles();
if (null!=subFiles){
for (File subFile : subFiles){
if (subFile.getName().endsWith(".shp")){
ShapefileDataStore shpDataStore = new ShapefileDataStore(subFile.toURI().toURL());
shpDataStore.setStringCharset(Charset.forName("GBK"));
// 获取地图要素
FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = shpDataStore.getFeatureSource();
//获取头属性信息
List<AttributeDescriptor> attributeDescriptors = featureSource.getSchema().getAttributeDescriptors();
List<Map<String, Object>> heads = new ArrayList<>();
for (AttributeDescriptor a:attributeDescriptors) {
Map<String, Object> et = new HashMap<>();
// System.out.println("字段名:"+a.getName());
String name = a.getName().toString();
et.put("name", name);
AttributeType type = a.getType();
Filter filter = type.getRestrictions().isEmpty() ? null : type.getRestrictions().get(0);
String typeLength = filter != null ? filter.toString() : "0";
Pattern pattern = Pattern.compile("[^0-9]");
Matcher matcher = pattern.matcher(typeLength);
String tLength = matcher.replaceAll("").trim();
// System.out.println("类型长度:"+tLength);
et.put("length", tLength);
String className = type.getBinding().getName();
String tName = className.substring(className.lastIndexOf(".") + 1);
// System.out.println("字段类型:"+tName);
//转数据库类型
if(tName.equals("MultiPolygon")){
tName = "geometry";
et.put("name", "geom");
}else if(tName.equals("Integer")){
tName = "numeric";
}else if(tName.equals("Double")){
tName = "float4";
et.put("length", 0);
}else{
tName = "varchar";
}
// System.out.println("字段类型转数据库类型后:"+tName);
et.put("type", tName);
heads.add(et);
}
//用shp文件名当表名
String tableName = subFile.getPath().substring(subFile.getPath().lastIndexOf("\")+1);
tableName = tableName.substring(0,tableName.lastIndexOf("."));
//创建图层数据表序列
geoserverDao.createSequence(tableName);
//创建图层数据表
geoserverDao.createTable(tableName,heads);
//获取数据
FeatureIterator<SimpleFeature> iterator = featureSource.getFeatures().features();
while(iterator.hasNext()) {
SimpleFeature feature = iterator.next();
feature.getName();
Iterator<Property> it = feature.getProperties().iterator();
LinkedHashMap<String, Object> data = new LinkedHashMap<>();
String geometry = "";
while (it.hasNext()) {
Property pro = it.next();
if (pro.getValue() instanceof Point) {//点
geometry = "'" +((Point) pro.getValue()).toString()+ "'";
data.put("geom",geometry);
} else if (pro.getValue() instanceof Polygon) {//面
geometry = "'" +((Polygon) pro.getValue()).toString()+ "'";
data.put("geom",geometry);
} else if (pro.getValue() instanceof MultiPolygon) {//多面
geometry = "'" +((MultiPolygon) pro.getValue()).toString()+ "'";
data.put("geom",geometry);
} else if (pro.getValue() instanceof LineString) {//线
geometry = "'" +((LineString) pro.getValue()).toString()+ "'";
data.put("geom",geometry);
} else {
data.put(pro.getName().toString(),pro.getValue());
}
}
data.put("creater_id",loginService.getEmployeeId());
data.put("create_time",new Timestamp(System.currentTimeMillis()));
//新增数据到图层数据表
geoserverDao.addTableDateList(tableName,heads,data);
//发布该图层
Boolean addLayer = geoServer.addLayer(null,null,tableName,null);
if(!addLayer){
throw new KspException(WebErrorCode.INTERNAL_PROCESS_ERROR, "发布数据图层失败", null, null);
}
}
}
}
}
}
}
上面所调用的dao方法:
public interface GeoserverDao {
@Update("CREATE SEQUENCE \"public\".\"${tableName}_seq\" ")
public void createSequence(@Param("tableName")String tableName);
@Update("")
public void createTable(@Param("tableName")String tableName,@Param("heads")List<Map<String, Object>> heads);
@Insert("")
public void addTableDateList(@Param("tableName")String tableName,@Param("heads")List<Map<String, Object>> heads,@Param("data")LinkedHashMap<String, Object> data);
}
2.通过rest发布geoserver图层
创建要用的工作区和数据储存:
引入geoserver依赖:
<dependency>
<groupId>nl.pdokgroupId>
<artifactId>geoserver-managerartifactId>
<version>1.7.0-pdok2version>
dependency>
配置文件:
geoserver:
#geoserver地址
url: http://192.168.2.4:9081/geoserver
#用户名
username: admin
#密码
password: geoserver
#工作区
shpworkspace: ksp
#数据存储
shpstorename: frm
imageworkspace: image
localdir:
style: protectedAreaGnfq
实现代码:
@Component
public class GeoServer {
private static Logger logger = LoggerFactory.getLogger(GeoServer.class);
/**
* geoServer配置
*/
private static String url;
private static String geoUsername;
private static String geoPassword;
//待发布矢量图层的工作区间
public static String shpWorkspace;
//待发布矢量图层的数据储存
public static String shpStorename;
//待发布影像图层的工作空间
public static String imageWorkspace;
public static String stylePath;
@Value("${geoserver.url}")
public void setUrl(String url) {
GeoServer.url = url;
}
@Value("${geoserver.username}")
public void setGeoUsername(String geoUsername) {
GeoServer.geoUsername = geoUsername;
}
@Value("${geoserver.password}")
public void setGeoPassword(String geoPassword) {
GeoServer.geoPassword = geoPassword;
}
@Value("${geoserver.shpworkspace}")
public void setShpWorkspace(String shpWorkspace) {
GeoServer.shpWorkspace = shpWorkspace;
}
@Value("${geoserver.shpstorename}")
public void setShpStorename(String shpStorename) {
GeoServer.shpStorename = shpStorename;
}
@Value("${geoserver.imageworkspace}")
public void setImageWorkspace(String imageWorkspace) {
GeoServer.imageWorkspace = imageWorkspace;
}
@Value("${localdir.style}")
public void setStylePath(String stylePath) {
GeoServer.stylePath = stylePath;
}
/**
* 判断工作区(workspace)是否存在,不存在则创建
*/
public Boolean judgeWorkSpace(String workspace){
try {
URL u = new URL(url);
GeoServerRESTManager manager = new GeoServerRESTManager(u, geoUsername, geoPassword);
GeoServerRESTPublisher publisher = manager.getPublisher();
List<String> workspaces = manager.getReader().getWorkspaceNames();
if (!workspaces.contains(workspace)) {
boolean createWorkspace = publisher.createWorkspace(workspace);
logger.info("create workspace : " + createWorkspace);
return createWorkspace;
} else {
logger.info("workspace已经存在了,workspace :" + workspace);
return true;
}
}catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断存储是否存在
* @param store 存储名
* @return boolean
*/
public static boolean shpJudgeDatabase(String store) {
try {
URL u = new URL(url);
GeoServerRESTManager manager = new GeoServerRESTManager(u, geoUsername, geoPassword);
GeoServerRESTPublisher publisher = manager.getPublisher();
RESTDataStore restStore = manager.getReader().getDatastore(shpWorkspace, store);
if (restStore == null) {
logger.info("数据存储不存在,可以创建!");
return true;
} else {
logger.info("数据存储已经存在了,store:" + store);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
* 方法一
* 直接发布shp文件到geoServer
* 将shp.zip通过http传递过去
* 不主动设置样式和编码
*
*
* @param fileUrl 本地文件地址 zip格式
* @param geocode 地理编码
* @return boolean
*/
public static boolean releaseShpByHttp(String fileUrl, String geocode) {
try {
File zipFile = new File(fileUrl);
//存储名/图层名
// String storeName = FileUtil.getFileNameNoEx(zipFile.getName());
String storeName = zipFile.getName();
GeoServerRESTReader reader = new GeoServerRESTReader(url, geoUsername, geoPassword);
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(url, geoUsername, geoPassword);
RESTLayer layer = reader.getLayer(shpWorkspace, storeName);
if (layer == null) {
if (publisher.publishShp(shpWorkspace, storeName, storeName, zipFile, geocode)) {
logger.info("图层发布成功:" + storeName);
return true;
} else {
logger.info("图层发布失败:" + storeName);
}
} else {
logger.info("图层已经发布过了:" + storeName);
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return false;
}
/**
* 方法二
* 向geoServer上传shp,并设置存储、图层名、样式和坐标系
*
* @param zipFilePath 压缩文件夹位置 完整文件地址
* @param storeName 存储、图层名 英文
* @param styleType 图层样式 shp工作空间下的对应样式
* @param coordinateSystem 坐标系 EPSG:4326
* @return boolean
*/
public boolean publishShp(String zipFilePath, String storeName, String styleType, String coordinateSystem) {
if (coordinateSystem == null) {
coordinateSystem = GeoServerRESTPublisher.DEFAULT_CRS;
}
try {
//创建发布类,放入用户名密码和url
GeoServerRESTPublisher geoServerRESTPublisher = new GeoServerRESTPublisher(url, geoUsername, geoPassword);
boolean b = geoServerRESTPublisher.publishShp(shpWorkspace, storeName,
new NameValuePair[]{new NameValuePair("charset", "GBK")},
//图层名称 指定用于发布资源的方法
storeName, GeoServerRESTPublisher.UploadMethod.FILE,
//zip图集的地址,直接压缩不要文件夹 坐标系 样式
new File(zipFilePath).toURI(), coordinateSystem, styleType);
if (b) {
return true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断图层是否已经存在,不存在则创建并发布
* @param workspace 工作区
* @param storename 数据存储
* @param tableName 表名
* @param coordinateSystem 坐标系 EPSG:4326
*/
public Boolean addLayer(String workspace,String storename,String tableName,String coordinateSystem){
if(workspace == null){
workspace = shpWorkspace;
}
if(storename == null){
storename = shpStorename;
}
if (coordinateSystem == null) {
coordinateSystem = GeoServerRESTPublisher.DEFAULT_CRS;
}
try {
URL u = new URL(url);
GeoServerRESTManager manager = new GeoServerRESTManager(u, geoUsername, geoPassword);
RESTLayer layer = manager.getReader().getLayer(workspace, tableName);
if(layer == null){//图层不存在
GSFeatureTypeEncoder pds = new GSFeatureTypeEncoder();
pds.setTitle(tableName);
pds.setName(tableName);
pds.setSRS(coordinateSystem);
GSLayerEncoder layerEncoder = new GSLayerEncoder();
boolean publish = manager.getPublisher().publishDBLayer(workspace, storename, pds, layerEncoder);
// manager.getPublisher().removeLayer()
System.out.println("图层发布publish : " + publish);
return publish;
}else {
System.out.println("该表图层已经发布过了,table:" + tableName);
return true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
* 删除图层
* @param workspace 工作区
* @param layerName 图层名
* @return
*/
public Boolean removeLayer(String workspace, String layerName){
try {
URL u = new URL(url);
GeoServerRESTManager manager = new GeoServerRESTManager(u, geoUsername, geoPassword);
RESTLayer layer = manager.getReader().getLayer(workspace, layerName);
if(layer != null){
boolean removeLayer = manager.getPublisher().removeLayer(workspace, layerName);
return removeLayer;
}else{
System.out.println("图层不存在, layer: " + layerName);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
* 上传图层样式文件到geoServer,sld文件
* 需要放入指定文件夹下
*
* @param styleType 样式文件名(不包含sld后缀)
* @return boolean
*/
public static boolean publishStyle(String styleType) {
try {
URL u = new URL(url);
GeoServerRESTManager manager = new GeoServerRESTManager(u, geoUsername, geoPassword);
GeoServerRESTReader reader = manager.getReader();
GeoServerRESTPublisher publisher = manager.getPublisher();
//读取style文件
String styleFile = stylePath + File.separator + styleType + ".sld";
File file = new File(styleFile);
//是否已经发布了改style
if (!reader.existsStyle(shpWorkspace, styleType)) {
publisher.publishStyleInWorkspace(shpWorkspace, file, styleType);
}
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
* 删除指定的数据存储
*
* @param workspace 工作区
* @param storeName 数据存储
* @return boolean
*/
public boolean removeStore(String workspace, String storeName) {
URL u = null;
try {
u = new URL(url);
GeoServerRESTManager manager = new GeoServerRESTManager(u, geoUsername, geoPassword);
GeoServerRESTStoreManager storeManager = manager.getStoreManager();
GSAbstractStoreEncoder gsAbstractStoreEncoder;
// manager.getPublisher().removeWorkspace();
if (shpWorkspace.equals(workspace)) {
gsAbstractStoreEncoder = new GSAbstractStoreEncoder(GeoServerRESTPublisher.StoreType.DATASTORES, storeName) {
@Override
protected String getValidType() {
return null;
}
};
gsAbstractStoreEncoder.setName(storeName);
return storeManager.remove(workspace, gsAbstractStoreEncoder, true);
}
if (imageWorkspace.equals(workspace)) {
gsAbstractStoreEncoder = new GSAbstractStoreEncoder(GeoServerRESTPublisher.StoreType.COVERAGESTORES, storeName) {
@Override
protected String getValidType() {
return null;
}
};
gsAbstractStoreEncoder.setName(storeName);
return storeManager.remove(workspace, gsAbstractStoreEncoder, true);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
}
3.成功发布后登录geoserver查看图层
点击左侧Layer Preview,再点击图层对应的OpenLayers
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)