Java 已知两个点的坐标经纬度以及方向角,判断两点是否相交,若相交求交点经纬度
时间: 2023-07-16 21:16:51 浏览: 166
判断两线段是否相交,相交求交点
4星 · 用户满意度95%
可以通过以下步骤来判断两个点是否相交并求出交点经纬度:
1. 将经纬度转换为平面坐标系中的直角坐标系,如墨卡托投影坐标系或UTM坐标系;
2. 根据方向角计算出两个点所在直线的解析式;
3. 判断两条直线是否相交,可以通过判断它们的斜率是否相等来判断;
4. 若两条直线相交,则求出它们的交点坐标;
5. 将交点坐标转换为经纬度坐标。
下面是 Java 代码示例:
```java
import java.awt.geom.Point2D;
public class Intersection {
// 计算两个点之间的距离
public static double distance(double lon1, double lat1, double lon2, double lat2) {
double R = 6371.0; // 地球半径,单位为千米
double radLat1 = Math.toRadians(lat1);
double radLat2 = Math.toRadians(lat2);
double a = radLat1 - radLat2;
double b = Math.toRadians(lon1) - Math.toRadians(lon2);
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 * R;
return s;
}
// 将经纬度转换为平面坐标系中的墨卡托投影坐标系
public static Point2D.Double mercator(double lon, double lat) {
double x = Math.toRadians(lon * 20037508.34 / 180);
double y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
y = y * 20037508.34 / 180;
return new Point2D.Double(x, y);
}
// 计算两点连线的方向角
public static double direction(double lon1, double lat1, double lon2, double lat2) {
double dx = lon2 - lon1;
double dy = lat2 - lat1;
double angle = Math.atan2(dy, dx);
return angle;
}
// 判断两条直线是否相交
public static boolean isIntersect(double lon1, double lat1, double dir1, double lon2, double lat2, double dir2) {
double k1 = Math.tan(dir1);
double k2 = Math.tan(dir2);
if (k1 == k2) { // 两条直线平行
return false;
} else {
double x1 = mercator(lon1, lat1).x;
double y1 = mercator(lon1, lat1).y;
double x2 = mercator(lon2, lat2).x;
double y2 = mercator(lon2, lat2).y;
double x = (k1*x1 - k2*x2 + y2 - y1) / (k1 - k2);
double y = k1 * (x - x1) + y1;
return true;
}
}
// 求两条直线的交点坐标
public static Point2D.Double intersection(double lon1, double lat1, double dir1, double lon2, double lat2, double dir2) {
double k1 = Math.tan(dir1);
double k2 = Math.tan(dir2);
double x1 = mercator(lon1, lat1).x;
double y1 = mercator(lon1, lat1).y;
double x2 = mercator(lon2, lat2).x;
double y2 = mercator(lon2, lat2).y;
double x = (k1*x1 - k2*x2 + y2 - y1) / (k1 - k2);
double y = k1 * (x - x1) + y1;
double lon = Math.toDegrees(x / 20037508.34 * 180);
double lat = Math.toDegrees(Math.atan(Math.exp(y / 20037508.34 * 180 * Math.PI / 180)) * 2 - Math.PI / 2);
return new Point2D.Double(lon, lat);
}
public static void main(String[] args) {
double lon1 = 116.3688;
double lat1 = 39.9155;
double lon2 = 116.4444;
double lat2 = 39.9318;
double dir1 = Math.toRadians(60);
double dir2 = Math.toRadians(150);
if (isIntersect(lon1, lat1, dir1, lon2, lat2, dir2)) {
Point2D.Double point = intersection(lon1, lat1, dir1, lon2, lat2, dir2);
System.out.println("交点经度:" + point.x);
System.out.println("交点纬度:" + point.y);
} else {
System.out.println("两条直线不相交");
}
}
}
```
阅读全文