天天看点

java判断经纬度是否在地图圆内

方法一 geodesy

<dependency>
              <groupId>org.gavaghan</groupId>
              <artifactId>geodesy</artifactId>
              <version>1.1.3</version>
        </dependency>
           
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid){

		//创建GeodeticCalculator,调用计算方法,传入坐标系、经纬度用于计算距离
		GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);

		return geoCurve.getEllipsoidalDistance();
	}

	public static void main(String[] args) throws IOException {
		GlobalCoordinates source = new GlobalCoordinates(30f, 110f);
		GlobalCoordinates target = new GlobalCoordinates(31f, 111f);

		double meter1 = getDistanceMeter(source, target, Ellipsoid.Sphere);
		double meter2 = getDistanceMeter(source, target, Ellipsoid.WGS84);

		System.out.println("Sphere坐标系计算结果:"+meter1 + "米");
		System.out.println("WGS84坐标系计算结果:"+meter2 + "米");
	}
           

方法二 GeoTools

<dependency>
            <groupId>org.locationtech</groupId>
            <artifactId>jts</artifactId>
            <version>1.13</version>
        </dependency>
           
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.operation.buffer.BufferOp;
import com.vividsolutions.jts.algorithm.PointLocator;

/**
	 * 判断经纬度是否在圆内
	 * @param lon 目标经度
	 * @param lat 目标纬度
	 * @param dis 距离,米
	 * @param centerLon 圆心经度
	 * @param centerLat 圆心纬度
	 * @return
	 */
	public static boolean inCircle(float lon, float lat,long dis,float centerLon,float centerLat){
		//创建一条直线
		Coordinate[] coordinates4 = new Coordinate[] {
				new Coordinate(centerLon,centerLat),
				new Coordinate(centerLon,centerLon+0.01f*dis/1000),
		};

		GeometryFactory gf=new GeometryFactory();
		Geometry gfLineString = gf.createLineString(coordinates4);
		double degree = dis / (2*Math.PI*6371004)*360; //将度换算成米,公式为:degree = meter / (2 * Math.PI * 6371004) * 360
		//缓冲区建立
		BufferOp bufOp = new BufferOp(gfLineString);
		bufOp.setEndCapStyle(BufferOp.CAP_BUTT);
		Geometry bg = bufOp.getResultGeometry(degree);
		//点是否在多边形内判断
		Coordinate point = new Coordinate(lon,lat);
		PointLocator a=new PointLocator();
		boolean p1=a.intersects(point, bg);
		if(p1) {
			System.out.println("point1:" + "该点在多边形内" + p1);
		}else {
			System.out.println("point1:" + "该点不在多边形内" + p1);
		}
		return p1;
	}