JTS-Distance常用操作

目录

  1. 求两点之间的球面距离
  2. 点到线段的最短距离、垂足、垂线

import java.io.FileNotFoundException;

import com.vividsolutions.jts.algorithm.distance.DistanceToPoint;
import com.vividsolutions.jts.algorithm.distance.PointPairDistance;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;


public class Distance {
	private static double EARTH_RADIUS = 6378137.0; // WGS84地球椭球体的半径,单位m

	//转为弧度
	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}


	/**
	 * 计算两个经纬度之间的球面距离
	 * @param lat1
	 * @param lng1
	 * @param lat2
	 * @param lng2
	 * @return
	 */
	public static double getDistance(double lat1, double lng1, double lat2,double lng2) {
		if(lat1<=0D || lng1<=0D || lat2<=0D || lng2<=0D){
			throw new RuntimeException("[经纬度必须大于0]");
		}
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000.0;
		return s;
	}

	/**
	 * 点到线段的最短距离,如果有垂足,锤线最短;如果没有垂线,点到端点的距离最短
	 * @param point
	 * @param line
	 */
	public static void footPoint(Point point, LineString line) {
		//定义垂线
		PointPairDistance pointPairDistance = new PointPairDistance();
		DistanceToPoint.computeDistance(line,point.getCoordinate(),pointPairDistance);
		//垂线的长度
		double length = pointPairDistance.getDistance();
		//垂足,锤线的第一个点
		Coordinate footCoord = pointPairDistance.getCoordinate(0);
	}

	/**
	 * 主函数
	 * @param args
	 * @throws FileNotFoundException
	 * @throws ParseException
	 */
	public static void main(String[] args) throws FileNotFoundException, ParseException {
		GeometryFactory gf = new GeometryFactory();
		Coordinate coord = new Coordinate();
		coord.x=115.73334;
		coord.y = 39.57573996;
		Geometry point = gf.createPoint(coord);
		System.out.println(getDistance(31.693982,121.014691,31.716261, 121.021174));

		WKTReader reader = new WKTReader(gf);
		LineString line = (LineString) reader.read("LINESTRING(118.46075166666667 39.31753333333333,118.461385 39.30982,118.462085 39.30172,118.462955 39.29372)");
		Coordinate coord1 = new Coordinate(118.408928,39.281301);
		Point point1 = gf.createPoint(coord);
		footPoint(point1,line);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值