Last active
March 12, 2021 03:19
-
-
Save tudk/a33de09ab60e97f3accdfbd1ef6faaaf to your computer and use it in GitHub Desktop.
calculating a point belonging to a region or not
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package vn.jupviec.wondermaid.tools.kmlreader.web.rest.util; | |
import java.io.Serializable; | |
import java.util.ArrayList; | |
import java.util.List; | |
public final class Geometry { | |
public static class LatLng implements Serializable { | |
private Double lat; | |
private Double lng; | |
public LatLng() { | |
} | |
public LatLng(Double lat, Double lng) { | |
this.lat = lat; | |
this.lng = lng; | |
} | |
public Double getLat() { | |
return lat; | |
} | |
public void setLat(Double lat) { | |
this.lat = lat; | |
} | |
public Double getLng() { | |
return lng; | |
} | |
public void setLng(Double lng) { | |
this.lng = lng; | |
} | |
@Override | |
public String toString() { | |
return "LatLng{" + | |
"lat=" + lat + | |
", lng=" + lng + | |
'}'; | |
} | |
} | |
private Geometry() { | |
} | |
private static <T> List<T> clone(List<T> org) { | |
List<T> copy = new ArrayList<>(org); | |
return copy; | |
} | |
public static boolean hasBelong(final LatLng point, List<LatLng> givenPolygon) { | |
if (givenPolygon.isEmpty()) { | |
return false; | |
} | |
List<LatLng> polygon = clone(givenPolygon); | |
if (!polygon.get(0).equals(polygon.get(polygon.size() - 1))) { | |
polygon.add(polygon.size(), polygon.get(0)); | |
} | |
int j = 0; | |
boolean oddNodes = false; | |
double x = point.getLat().doubleValue(); | |
double y = point.getLng().doubleValue(); | |
int n = polygon.size(); | |
for (int i = 0; i < n; i++) { | |
j++; | |
if (j == n) { | |
j = 0; | |
} | |
double lngI = polygon.get(i).getLng().doubleValue(); | |
double lngJ = polygon.get(j).getLng().doubleValue(); | |
double latI = polygon.get(i).getLat().doubleValue(); | |
double latJ = polygon.get(j).getLat().doubleValue(); | |
if ((lngI > y) != (lngJ > y) && | |
(x < (latJ - latI) * (y - lngI) / (lngJ - lngI) + latI)) { | |
oddNodes = !oddNodes; | |
} | |
} | |
return oddNodes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment