需求
给定4个经纬度坐标,构建成一个多边形,判断某个经纬度是否在多边形范围内。
拾取经纬度坐标:http://api.map.baidu.com/lbsapi/getpoint/index.html
引入包
implementation 'org.locationtech.jts:jts-core:1.17.0'
构建一个工具类,返回绘制的多边形
package cn.unuuc.cwl.cwldemoadmin.util;
import cn.unuuc.cwl.cwldemoadmin.vo.FencePosition;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Polygon;
import java.util.ArrayList;
import java.util.List;
/**
* @author 陈威龙
* @date 2023/9/7 11:10
*/
public class JtsCoreUtils {
private static List<FencePosition> fencePositionList = new ArrayList<>();
static {
fencePositionList.add(new FencePosition("119.829328","32.305446"));
fencePositionList.add(new FencePosition("119.863104","32.294948"));
fencePositionList.add(new FencePosition("119.884619","32.519718"));
fencePositionList.add(new FencePosition("119.877504","32.51984"));
fencePositionList.add(new FencePosition("119.829328","32.305446"));
}
public static Polygon createPolygon(){
Coordinate[] polygonCoordinates = new Coordinate[fencePositionList.size()];
for (int i = 0; i < fencePositionList.size(); i++) {
FencePosition fencePosition = fencePositionList.get(i);
polygonCoordinates[i] = new Coordinate(Double.parseDouble(fencePosition.getLongitude()), Double.parseDouble(fencePosition.getLatitude()));
}
// 创建多边形对象
return new GeometryFactory().createPolygon(polygonCoordinates);
}
}
注意:
- 绘制多边形,第一个和最后一个经纬度信息要一样,要构成回路
根据经纬度构建一个点Point
Coordinate testPoint = new Coordinate(120.012897, 32.517587);
GeometryFactory geometryFactory = new GeometryFactory();
Point point = geometryFactory.createPoint(testPoint);
判断
@SpringBootTest
class CwlDemoAdminApplicationTests {
@Test
void contextLoads() {
// 120.012897,32.517587
Coordinate testPoint = new Coordinate(120.012897, 32.517587);
GeometryFactory geometryFactory = new GeometryFactory();
Point point = geometryFactory.createPoint(testPoint);
Polygon coordinate = JtsCoreUtils.createPolygon();
boolean contains = coordinate.contains(point);
if(contains){
System.out.println("在范围内");
}else {
System.out.println("不在范围内");
}
}
}
输出: 不在范围内
评论区