这里写自定义目录标题

  • Java geotools 坐标转换
    • 点坐标转换
      • pom文件
      • 代码
    • shp坐标系转换

Java geotools 坐标转换

点坐标转换

我点坐标转换为4326到3857,虽然我平时都是4546到3857,都一样。主要时因为我手里没有4546的坐标,

pom文件

这个geotools的依赖比较“皮干”,要是下载不成功,就去官网geotools下的quickstart 的Mavenquick quickstart下面找仓库地址。

  <repositories><repository><id>osgeo</id><name>OSGeo Release Repository</name><url>https://repo.osgeo.org/repository/release/</url><snapshots><enabled>false</enabled></snapshots><releases><enabled>true</enabled></releases></repository><repository><id>osgeo-snapshot</id><name>OSGeo Snapshot Repository</name><url>https://repo.osgeo.org/repository/snapshot/</url><snapshots><enabled>true</enabled></snapshots><releases><enabled>false</enabled></releases></repository></repositories><dependency><groupId>org.geotools</groupId><artifactId>gt-epsg-hsql</artifactId><version>20.0</version></dependency>
```<dependency><groupId>org.geotools</groupId><artifactId>gt-referencing</artifactId><version>20.0</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-api</artifactId><version>20.0</version></dependency>

代码

package com.wangkang.gts4vect;import org.geotools.geometry.jts.JTS;import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;import java.text.DecimalFormat;public class MyGeotools {public static void main(String[] args) {//        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
//        WKTReader reader = new WKTReader( geometryFactory );//某点的经纬度Double y = 34.26095856;Double x = 108.94237668;Double[] coordinate = getCoordinate(x, y);System.out.println(coordinate[0] + " " + coordinate[1]);}//坐标转换public static Double[] getCoordinate(Double x, Double y) {Double[] res = new Double[2];Coordinate tar = null;try {//封装点,这个是通用的,也可以用POINT(y,x)// private static WKTReader reader = new WKTReader( geometryFactory );Coordinate sour = new Coordinate(y, x);//这里要选择转换的坐标系是可以随意更换的CoordinateReferenceSystem source = CRS.decode("EPSG:4326");CoordinateReferenceSystem target = CRS.decode("EPSG:3857");//建立转换,下面两个我屏掉的转换方式会报出需要3/7参数的异常// MathTransform mathTransform = CRS.findMathTransform(source, target);//MathTransform mathTransform1 = CRS.findMathTransform(source, target, false);MathTransform transform = CRS.findMathTransform(source, target, true);tar = new Coordinate();//转换JTS.transform(sour, tar, transform);} catch (FactoryException | org.opengis.referencing.operation.TransformException e) {e.printStackTrace();}String[] split = (tar.toString().substring(1, tar.toString().length() - 1)).split(",");//经纬度精度DecimalFormat fm = new DecimalFormat("0.0000000");res[0] = Double.valueOf(fm.format(Double.valueOf(split[0])));res[1] = Double.valueOf(fm.format(Double.valueOf(split[1])));return res;}
}

结果如下

在这个转换类中,x,y 的位置调换了,这个是我们国家和国外的差异,约定成俗的东西,记住就好,为什么呢?因为不记住接下来的shp坐标系转换图像就飘了,飘到。。。。
如果说整个科学技术不好看,好吧,我再换种写法

package com.wangkang.gts4vect;import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;import java.text.DecimalFormat;public class MyGeotools2 {static  GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();static  WKTReader reader = new WKTReader( geometryFactory );public static void main(String[] args) {//某点的经纬度Double y=34.26095856;Double x=108.94237668;try {//封装点,x,y 要反过来,不反过来就报纬度超过90的异常String point="POINT("+y+" "+x+")";Geometry geometry = reader.read(point);//这里要选择转换的坐标系是可以随意更换的CoordinateReferenceSystem source = CRS.decode("EPSG:4326");CoordinateReferenceSystem target = CRS.decode("EPSG:3857");//建立转换,下面两个我屏掉的转换方式会报出需要3/7参数的异常// MathTransform mathTransform = CRS.findMathTransform(source, target);//MathTransform mathTransform1 = CRS.findMathTransform(source, target, false);MathTransform transform = CRS.findMathTransform(source, target,true);//转换Geometry transform1 = JTS.transform(geometry, transform);System.out.println(transform1);} catch (FactoryException | TransformException | ParseException e) {e.printStackTrace();}}}

结果如下

其实整个转化就两句代码
MathTransform transform = CRS.findMathTransform(source, target,true);
Geometry transform1 = JTS.transform(geometry, transform);
就这两句。

shp坐标系转换

依赖自己整,上工具类

package com.wangkang.gts4vect;import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStoreFactorySpi;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import static org.geotools.data.Transaction.AUTO_COMMIT;import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;public class geotools3 {private static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory( null );private static WKTReader reader = new WKTReader( geometryFactory );/*** 单个geom转换* geotools的安装包中的x,y坐标是反着的,因此,直接用geomtry转换,导出的数据是错误,先的将* x,y的坐标换过来。所以,我选择拼装geomtry。* @param geom* @return*/public static Geometry lonlat2WebMactor(Geometry geom,String epsg){try{//CoordinateReferenceSystem的生成方法有两种,EPSG和WKT,然而,我发现把我需要的坐标系的prj文件中的内容用来转换会报“不存在。。。。什么这样的。。”//所以采用EPSG,即使使用了EPSG,导出的转换后的投影文件的prj仍然不对,arcgis 无法识别。当然,同一个坐标系下的prj 文件的内容是相同的,用别的替换即可。CoordinateReferenceSystem crsresource = CRS.decode("EPSG:"+epsg);CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:3857");//CoordinateReferenceSystem crsTarget = CRS.decode(strWKTMercator);// 投影转换MathTransform transform = CRS.findMathTransform(crsresource, crsTarget,true);String geom1 = geom.toString();String[] split = geom1.substring(geom1.lastIndexOf("(")+1, geom1.length() - 3).split(",");StringBuffer res=new StringBuffer();res.append("MULTIPOLYGON (((");for(int i=0;i<split.length;i++){int space = split[i].lastIndexOf(" ");Double x=Double.valueOf(split[i].substring(0,space).trim());Double y=Double.valueOf(split[i].substring(space).trim());//使用coordinate时,产生的结果dest中的x坐标的位数是科学计数
//                Coordinate source = new Coordinate(y, x);
//                Coordinate dest = new Coordinate();
//                JTS.transform(source,dest, transform);
//                String[] str = dest.toString().substring(1, dest.toString().length() - 1).split(",");String point="POINT("+y+" "+x+")";Geometry pointGeom = reader.read(point);Geometry resGeom = JTS.transform(pointGeom, transform);String[] str = resGeom.toString().substring(resGeom.toString().lastIndexOf("(")+1, resGeom.toString().length() - 1).split("\\s+");res.append(str[0]+" "+str[1]+",");}String result = res.substring(0, res.length() - 1);result=result+")))";Geometry read = reader.read(result);return read;}catch (Exception e) {e.printStackTrace();return null;}}/*** 坐标转换:WGS84转墨卡托* shp文件坐标转换。本质是每一个geom转换* @param inputShp shp输入路径* @param outputShp shp输出路径     * * @param  epsg 输入文件的epsg*/public void projectShape(String inputShp, String outputShp,String epsg){try {//源shape文件ShapefileDataStore shapeDS = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(new File(inputShp).toURI().toURL());//创建目标shape文件对象Map<String, Serializable> params = new HashMap<String, Serializable>();FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();params.put(ShapefileDataStoreFactory.URLP.key, new File(outputShp).toURI().toURL());ShapefileDataStore ds = (ShapefileDataStore) factory.createNewDataStore(params);// 设置属性SimpleFeatureSource fs = shapeDS.getFeatureSource(shapeDS.getTypeNames()[0]);//CoordinateReferenceSystem crs = CRS.parseWKT(strWKTMercator);CoordinateReferenceSystem crs = CRS.decode("EPSG:3857");ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(),crs));//设置writerFeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0],AUTO_COMMIT);//写记录SimpleFeatureIterator it = fs.getFeatures().features();try {while (it.hasNext()) {SimpleFeature f = it.next();SimpleFeature fNew = writer.next();fNew.setAttributes(f.getAttributes());//每个geom转换Geometry geom = lonlat2WebMactor((Geometry)f.getAttribute("the_geom"),epsg);fNew.setAttribute("the_geom", geom);}}finally {it.close();}writer.write();writer.close();ds.dispose();shapeDS.dispose();}catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {}}

上面的只能转换面,写的也很蹩脚,令人痛心疾首,所以lonlat2WebMactor方法更新如下

   try{        CoordinateReferenceSystem crsresource = CRS.decode("EPSG:"+epsg);CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:3857");// 投影转换MathTransform transform = CRS.findMathTransform(crsresource, crsTarget,true);Coordinate[] coordinates = geom.getCoordinates();for (Coordinate coordinate : coordinates) {               double x = coordinate.getX();coordinate.setX(coordinate.getY());coordinate.setY(x);}Geometry transform1 = JTS.transform(geom, transform);return transform1;}catch (Exception e) {e.printStackTrace();return null;}

转换的功能已经完成了。
需要注意的是:
1.转换完成后(我这里是3857),prj的文件内容是有问题的。arcgis,QGIS并不能识别这个空间坐标系
如图:有问题的

用arcgis转换出的3857的prj是:

String prj="PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\","+ "GEOGCS[\"GCS_WGS_1984\","+ "DATUM[\"D_WGS_1984\","+ "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],"+ "PRIMEM[\"Greenwich\",0.0],"+ "UNIT[\"Degree\",0.0174532925199433]],"+ "PROJECTION[\"Mercator_Auxiliary_Sphere\"],"+ "PARAMETER[\"False_Easting\",0.0],"+ "PARAMETER[\"False_Northing\",0.0],"+ "PARAMETER[\"Central_Meridian\",0.0],"+ "PARAMETER[\"Standard_Parallel_1\",0.0],"+ "PARAMETER[\"Auxiliary_Sphere_Type\",0.0],"+ "UNIT[\"Meter\",1.0]]";

测试阶段,可以手动把prj的内容替换了。我用的时候写了一个扣JIO的东西。目的,替换prj中的内容

package com.suntoon.util;import com.suntoon.mapper.CoordinateSystemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.io.*;
@Component
public class PrjUtil {/*** 修改prj文件中的坐标系* path:prj文件的全路径*/public void editPrj(String path){final String MKT84 = "PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\","+ "GEOGCS[\"GCS_WGS_1984\","+ "DATUM[\"D_WGS_1984\","+ "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],"+ "PRIMEM[\"Greenwich\",0.0],"+ "UNIT[\"Degree\",0.0174532925199433]],"+ "PROJECTION[\"Mercator_Auxiliary_Sphere\"],"+ "PARAMETER[\"False_Easting\",0.0],"+ "PARAMETER[\"False_Northing\",0.0],"+ "PARAMETER[\"Central_Meridian\",0.0],"+ "PARAMETER[\"Standard_Parallel_1\",0.0],"+ "PARAMETER[\"Auxiliary_Sphere_Type\",0.0],"+ "UNIT[\"Meter\",1.0]]";File file = new File(path);try (FileOutputStream outputStream = new FileOutputStream(file);OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"utf-8");BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);){bufferedWriter.write(MKT84);} catch (IOException e) {e.printStackTrace();}}}

2.切记x,y是位置换了的,不然,有时候不会报错,改完prj的文件arcgis可以打开,但是,和用arcgis转出的图层的样子,属性内容是一样的,但是坐标不对(可以发布看下返回链接的bbox的经纬度,也可以几何计算看看)。
3.我把用arcgis转换和用geotools转换的结果做了对比
geotools:

arcgis:

但从边界看起来,似乎是有误差,而且误差不小。但是,坐标是一摸一样的。在显示的位数中,没有误差。后来放大图层,观看边界,发现图形是完全重合的。这个显示的问题并不会影响获取属性数据。

java geotools 坐标转换相关推荐

  1. java基于geotools实现的几何图形坐标系转换通用工具类,geotools几何坐标转换,java几何坐标转换

    在GIS开发中,前端地图通常使用地理坐标,而后端在计算几何面积等操作时,需要使用投影坐标.这过程中则需要进行坐标转换.下面带来了一个Java基于geotools开发的坐标转换工具类,支持点.线.面等几 ...

  2. Java+GeoTools工具包+读写shapfile文件

    本篇所用到的测试shapfile文件下载地址: 链接: https://pan.baidu.com/s/1S-TrFp_r8zyf_d0oBUeWqg GeoTools英文帮助文档地址: Geotoo ...

  3. Java经纬度坐标转换到平面坐标

    米勒坐标系 package sg.edu.ntu.huangcheng;public class MillerCoordinate {public static double[] MillierCon ...

  4. java 地图坐标转换_百度地图坐标和高德地图坐标转换代码 Java实现

    最近做项目需要百度地图坐标转换到高德地图坐标,高德官方也给出了转换接口(百度地图也给出了转换接口) http://lbs.amap.com/api/javascript-api/reference/l ...

  5. java 地图坐标转换_百度地图经纬度和地址互转(Java代码)

    这是基于springmvc+mybatis 的一个controller.如果不是这个框架,可以把方法实体抽到自己写的一个类中,然后再测试 package com.uwitec.controller.s ...

  6. 【Java】 # java实现坐标转换工具类

    1. 主流坐标系简介 WGS84坐标系 地球坐标系,国际上通用的坐标系 使用GPS芯片或者北斗芯片的设备,获取的经纬度就是WGS84地理坐标系. 地图API:谷歌地图使用的是WGS84坐标系,但是中国 ...

  7. java的坐标转换_java版本坐标转换

    1 /* * 2 * 各地图API坐标系统比较与转换; 3 * WGS84坐标系:即地球坐标系,国际上通用的坐标系.设备一般包含GPS芯片或者北斗芯片获取的经纬度为WGS84地理坐标系, 4 * 谷歌 ...

  8. java 经纬度坐标转换 WGS84、火星坐标 (GCJ-02)、百度坐标 (BD-09)

    会有偏移,但是还能接受 WGS84 国际标准,从 GPS 设备中取出的数据的坐标系 国际地图提供商使用的坐标系 火星坐标 (GCJ-02) 中国标准,从国行移动设备中定位获取的坐标数据使用这个坐标系 ...

  9. GeoTools学习参考文章

    参考文章汇总: geotools学习(一)IntelliJ快速入门 geotools学习(二)要素 geotools学习(三) 坐标系 geotools学习(四)查询 geotools学习(五)影像 ...

最新文章

  1. JS获取客户端IP地址、MAC和主机名的7个方法汇总
  2. Tomcat源码分析(六)--日志记录器和国际化
  3. 在计算机术语中 将ALU控制器和,计算机组成原理试题与答案
  4. SAP 外向交货的包装功能实现
  5. 电脑大小写怎么切换_苹果怎么切换电脑便签?可以自由切换的电脑便签手机日历怎么备注特殊日子?苹果手机日历特殊日子提醒便签...
  6. Java经典实例:比较浮点数
  7. DOM-13 【实战】输入及状态改变事件、京东搜索框
  8. 用Mysql网页式管理工具安全地访问数据库的方法
  9. caffe2安装篇(二) ubuntu16.04 安装方法
  10. vue3 线上环境 ctx 无法识别
  11. JDBC05 ResultSet结果集
  12. Android 文本监听接口TextWatcher详解
  13. java 文件上传(使用多线程)
  14. memcached 详解
  15. priority java_java基础—-多线程之priority(四)
  16. 华三路由器配置mstp多生成树协议
  17. 【谷粒学院项目开发44】课程大纲——小节的添删
  18. 零基础搭建Tomcat集群(超详细)
  19. 信息安全行业从业指南2.0
  20. vs community 2019安装失败问题解决

热门文章

  1. Mysql使用sql语句建表
  2. MYSQL Error: 1089 - Incorrect sub part key; the used key part isn't a string...
  3. Distill详述「可微图像参数化」:神经网络可视化和风格迁移利器!
  4. keychron矮轴无线机械键盘简直就是yyds
  5. 高级控件——列表类视图——基本适配器BaseAdapter
  6. python中docx模板合并多个word文档
  7. 三菱模拟量fx3u4da_FX3U-4DA-ADP用户手册三菱FX3U-4DA-ADP模拟量控制篇手册 - 广州凌控...
  8. 汇总二,js系列-css系列-其他综合系列
  9. mysql数据库的分页
  10. QT4.8.7 打开Mupdf