?判斷一個經緯度是否落在一個指定的區域范圍內有多種實現方式比如:調用地圖API,Path2D 包和射線法等多種方式,這里用的是Path2D 包來實現 ,這是它的api文檔Path2D-api
/** * 使用Path2D創建一個多邊形
* @param polygon 經緯度 集合
* @return 返回Path2D.Double
*/
private static Path2D.Double create(List<ScopeRequest> polygon) {? ? ? ? //創建path2D對象
? ? ? ? Path2D.Double generalPath = new Path2D.Double();
? ? ? ? //獲取第一個起點經緯度的坐標
? ? ? ? ScopeRequest first = polygon.get(0);
? ? ? ? // 通過移動到以double精度指定的指定坐標,把第一個起點添加到路徑中
? ? ? ? generalPath.moveTo(first.getLongitude(), first.getLatitude());
? ? ? ? //把集合中的第一個點刪除防止重復添加
? ? ? ? polygon.remove(0);
? ? ? ? //循環集合里剩下的所有經緯度坐標
? ? ? ? for (ScopeRequest d : polygon) {
? ? ? ? ? ? // 通過從當前坐標繪制直線到以double精度指定的新指定坐標,將路徑添加到路徑。
????????????//從第一個點開始,不斷往后繪制經緯度點?
? ? ? ? ? ? generalPath.lineTo(d.getLongitude(), d.getLatitude());
? ? ? ? }
? ? ? ? // 最后要多邊形進行封閉,起點及終點
? ? ? ? generalPath.lineTo(first.getLongitude(), first.getLatitude());
? ? ? ? // 將直線繪制回最后一個?moveTo的坐標來關閉當前子路徑。
? ? ? ? generalPath.closePath();
? ? ? ? return generalPath;
? ? }
/**
? ? * 判斷點是否在區域內
? ? * @param polygon? 區域經緯度json字符串
? ? * @param longitude 經度
? ? * @param latitude? 緯度
? ? * @return 返回true跟false
? ? */
? ? public static boolean isPoint(String polygon, double longitude, double latitude) {
? ? ? ? JSONArray jsonArray = JSON.parseArray(polygon);
? ? ? ? //將json轉換成對象
? ? ? ? List<ScopeRequest> list = JSON.parseArray(jsonArray.toJSONString(), ScopeRequest.class);
? ? ? ? Path2D path2D = create(list);
????????// true如果指定的坐標在Shape邊界內;?否則為false?。
? ? ? ? return path2D.contains(longitude, latitude);
? ? }
public class ScopeRequest {
? ? private Double longitude;
? ? private Double latitude;
? ? public ScopeRequest(){}
? ? public ScopeRequest(Double longitude,Double latitude){
? ? ? ? this.longitude = longitude;
? ? ? ? this.latitude = latitude;
? ? }
}