判断点是否在多边形内,如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
package com
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OrderMapTests {
public static void main(String[] args) {
Map<String, String> orderLocation = new HashMap<String, String>();
orderLocation.put("X", "117.219116");
orderLocation.put("Y", "31.839064");
String partitionLocation = "31.839064 117.219116,31.83253 117.219403,31.828511 117.218146,31.826763 117.219259,31.826118 117.220517,31.822713 117.23586,31.822958 117.238375,31.838512 117.23798,31.839617 117.226194,31.839586 117.222925";
System.out.println(isInPolygon(orderLocation, partitionLocation));
}
public static boolean isInPolygon(Map<String, String> orderLocation,String partitionLocation){
double p_x =Double.parseDouble(orderLocation.get("X"));
double p_y =Double.parseDouble(orderLocation.get("Y"));
Point2D.Double point = new Point2D.Double(p_x, p_y);
List<Point2D.Double> pointList= new ArrayList<Point2D.Double>();
String[] strList = partitionLocation.split(",");
for (String str : strList){
String[] points = str.split(" ");
double polygonPoint_x=Double.parseDouble(points[1]);
double polygonPoint_y=Double.parseDouble(points[0]);
Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x,polygonPoint_y);
pointList.add(polygonPoint);
}
return IsPtInPoly(point,pointList);
}
public static 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 static boolean IsPtInPoly(Point2D.Double point, List<Point2D.Double> pts){
int N = pts.size();
boolean boundOrVertex = true;
int intersectCount = 0;
double precision = 2e-10;
Point2D.Double p1, p2;
Point2D.Double p = point;
p1 = pts.get(0);
for(int i = 1; i <= N; ++i){
if(p.equals(p1)){
return boundOrVertex;
}
p2 = pts.get(i % N);
if(p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)){
p1 = p2;
continue;
}
if(p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)){
if(p.y <= Math.max(p1.y, p2.y)){
if(p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)){
return boundOrVertex;
}
if(p1.y == p2.y){
if(p1.y == p.y){
return boundOrVertex;
}else{
++intersectCount;
}
}else{
double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;
if(Math.abs(p.y - xinters) < precision){
return boundOrVertex;
}
if(p.y < xinters){
++intersectCount;
}
}
}
}else{
if(p.x == p2.x && p.y <= p2.y){
Point2D.Double p3 = pts.get((i+1) % N);
if(p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)){
++intersectCount;
}else{
intersectCount += 2;
}
}
}
p1 = p2;
}
if(intersectCount % 2 == 0){
return false;
} else {
return true;
}
}
}