侧边栏壁纸
博主头像
实习两年半

基础不牢,地动山摇。

  • 累计撰写 43 篇文章
  • 累计创建 40 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录

经纬度判断是否在一个范围内

实习两年半
2023-09-07 / 0 评论 / 0 点赞 / 925 阅读 / 383 字
温馨提示:
本文最后更新于 2023-09-28,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

需求

给定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("不在范围内");
       }
   }

}

输出: 不在范围内

0

评论区