Java 判断 一个点是不是在一个多边形围起来
MobilelocationEntity 是手机位置信息类 包含经度纬度
Enclosure 围栏类 每一个对象是形成多边形围栏的一个点 包含经度纬度
[java] view plain copy
package com.sdunicomsi.util.map;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import com.sdunicomsi.cgzft.entity.gis.Enclosure;
import com.sdunicomsi.cgzft.entity.gis.MobilelocationEntity;
/**
*
* @author lxg
*
*/
public class MapTools {
/**
* 判断当前位置是否在围栏内
* @param mobilelocationEntity
* @param enclosureList
* @return
*/
public static boolean isInPolygon(MobilelocationEntity mobilelocationEntity,List<Enclosure> enclosureList){
double p_x =Double.parseDouble(mobilelocationEntity.getLongitude());
double p_y =Double.parseDouble(mobilelocationEntity.getLatitude());
Point2D.Double point = new Point2D.Double(p_x, p_y);
List<Point2D.Double> pointList= new ArrayList<Point2D.Double>();
for (Enclosure enclosure : enclosureList){
double polygonPoint_x=enclosure.getLongitude();
double polygonPoint_y=enclosure.getLatitude();
Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x,polygonPoint_y);
pointList.add(polygonPoint);
}
MapTools test = new MapTools();
return test.checkWithJdkGeneralPath(point,pointList);
}
/**
* 返回一个点是否在一个多边形区域内
* @param point
* @param polygon
* @return
*/
private boolean checkWithJdkGeneralPath(Point2D.Double point, List<Point2D.Double> polygon) {
java.awt.geom.GeneralPath p = new java.awt.geom.GeneralPath();
Point2D.Double first = polygon.get(0);
p.moveTo(first.x, first.y);
polygon.remove(0);
for (Point2D.Double d : polygon) {
p.lineTo(d.x, d.y);
}
p.lineTo(first.x, first.y);
p.closePath();
return p.contains(point);
}
}
第二种方法
// 方法二
// 方法二
public boolean checkWithJdkPolygon(Point2D.Double point, List<Point2D.Double> polygon) {
java.awt.Polygon p = new Polygon();
// java.awt.geom.GeneralPath
final int TIMES = 1000;
for (Point2D.Double d : polygon) {
int x = (int) d.x * TIMES;
int y = (int) d.y * TIMES;
p.addPoint(x, y);
}
int x = (int) point.x * TIMES;
int y = (int) point.y * TIMES;
return p.contains(x, y);
}
[java] view plain copy
[java] view plain copy