根据经纬度,判断点位是否在范围内(多边形内)
问题描述:
-
有个需求,需要判断一个点位,在多边形内,并展示出来,研究了许多方法,还是这个射线法比较简单好用
-
数据库的 coordinate多边形字段存储如下:
129.26203608256768,26.085271312376 129.26801230123188,26.085807124332913 129.26858068565312,26.0231714249 129.26524138157777,26.0780112349326908 129.2601231480449,26.08158773429283 129.26203608256768,26.081231310453276
由多个经纬度,组成一个多边形的形状,逗号区分经纬度,空格隔开多个坐标的存储方式(不同地方不一样)
最终效果如下:
代码部分:
- 代码思路:1、写好判断点位的方法 2、切割多边形,并存入List集合
1、判断是否在点位的方法( 用于判断点 (x0, y0) 是否在给定多边形 ps 内部的方法 )
/**
* 判断点是否在范围内 , (point类的代码在下面)
* @param x0
* @param y0
* @param ps - > ps集合 存放coordiante切割的多个经纬度点
* @return
*/
public boolean contations(double x0, double y0, List<Point> ps) {
int crossings = 0;
for (int i = 0; i < ps.size() - 1; i++) {
double slope = (ps.get(i + 1).getY() - ps.get(i).getY()) / (ps.get(i + 1).getX() - ps.get(i).getX());
boolean cond1 = (ps.get(i).getX() <= x0) && (x0 < ps.get(i + 1).getX());
boolean cond2 = (ps.get(i + 1).getX() <= x0) && (x0 < ps.get(i).getX());
boolean above = (y0 < slope * (x0 - ps.get(i).getX()) + ps.get(i).getY());
if ((cond1 || cond2) && above) {
crossings++;
}
}
return (crossings % 2 != 0);
}
2、Point类(简易版)
@data
public class Point {
public Point(double x0, double y0){
this.x = x0;
this.y = y0;
}
/**
*
*/
private double x;
/**
*
*/
private double y;
}
3、切割coordinate 并存入List集合去判断
List<Point> points = new ArrayList<Point>();
if (StringUtils.isNotBlank(coor)) {
String[] cs = coor.split(" ");
for (int i = 0; i < cs.length; i++) {
String s = cs[i];
if(StringUtils.isBlank(s)){
continue;
}
String[] xy = s.split(",");
Double x = new Double(xy[0]);
Double y = null;
try {
y = new Double(xy[1]);
} catch (Exception e) {
//System.out.println(xy[1]);
//System.out.println(l.getStr("areacode"));
throw new RuntimeException(e.getMessage(), e);
}
//所有的点 都存入这里
points.add(new Point(x, y));
}
}
4、最后的判断 是否在点位内
if( contations( lon,lat,points ) ){
sout("存在多变形内");
}else{
sout("不存在多变形内");
}