Commit ee1ccf2f by 查志伟

Merge branch '20210913-购物车配送费代码优化-zhiwei.zha'

parents ae4093a8 f61715bc
......@@ -22,7 +22,7 @@ public class BizDTO {
private DeliveryInfoDTO deliveryInfo;
/**
*
* 门店基础信息
*/
private StoreInfoDTO storeInfo;
}
......@@ -171,4 +171,8 @@ public class StoreInfoDTO {
*/
private String thirdPartCode;
/**
* 配送范围
*/
private String distributionScope ;
}
package cn.freemud.entities.dto.store;
import lombok.Builder;
import lombok.Data;
/**
* @author : xh.Z
* @email : fisherman0510@163.com
* @Date : 2021/6/4 下午1:53
* @description :
*/
@Data
@Builder
public class GetEstimateDeliveryRequest extends StoreInfoRequestDto {
/**
* 用户收货地址维度
*/
private String latitude;
/**
* 用户收货地址经度
*/
private String longitude;
}
package cn.freemud.entities.dto.store;
import lombok.Builder;
import lombok.Data;
import java.util.Date;
/**
* @author : xh.Z
* @email : fisherman0510@163.com
* @Date : 2021/6/4 下午3:42
* @description :
*/
@Data
@Builder
public class QueryDeliverDetailResponse {
/**
* 预计送达时间
*/
private Date expectArriveTime;
}
/**
* All rights Reserved, Designed By www.freemud.cn
*
* @Title: StoreBaseResponseDto
* @Package cn.freemud.entities.dto
* @Description:
* @author: ping.wu
* @date: 2018/5/28 19:13
* @version V1.0
* @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
* 注意:本内容仅限于上海非码科技内部传阅,禁止外泄以及用于其他的商业目
*/
package cn.freemud.entities.dto.store;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class StoreBaseResponseDto<T> {
Integer statusCode;
String msg;
T bizVO;
}
package cn.freemud.entities.dto.store;
import lombok.Data;
/**
* @author : xh.Z
* @email : fisherman0510@163.com
* @Date : 2021/6/16 上午9:57
* @description :
*/
@Data
public class StoreCBaseResponse<T> {
private String code;
private String message;
private T result;
private String ver;
}
package cn.freemud.entities.dto.store;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* @author : xh.Z
* @email : fisherman0510@163.com
* @Date : 2021/6/17 上午11:36
* @description :
*/
@Data
public class StoreCBaseResponseDto {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date expectArriveTime;
/**
* 新配送费
*/
private Long deliveryAmount;
/**
* 配送费为零的原因:0:正常,1:超出配送范围
*/
private Integer deliveryFeeZeroReason;
}
/**
* All rights Reserved, Designed By www.freemud.cn
*
* @Title: StoreInfoRequestDto
* @Package cn.freemud.entities.dto
* @Description:
* @author: ping.wu
* @date: 2018/5/14 16:42
* @version V1.0
* @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
* 注意:本内容仅限于上海非码科技内部传阅,禁止外泄以及用于其他的商业目
*/
package cn.freemud.entities.dto.store;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class StoreInfoRequestDto {
private String partnerId;
private String storeCode;
public StoreInfoRequestDto(String partnerId, String storeCode) {
this.partnerId = partnerId;
this.storeCode = storeCode;
}
}
......@@ -13,46 +13,39 @@
package cn.freemud.service.delivery.impl;
import cn.freemud.constant.ApplicationConstant;
import cn.freemud.entities.dto.store.GetEstimateDeliveryRequest;
import cn.freemud.entities.dto.store.StoreCBaseResponse;
import cn.freemud.entities.dto.store.StoreCBaseResponseDto;
import cn.freemud.entities.dto.console.*;
import cn.freemud.entities.vo.QueryDeliveryDistanceRequest;
import cn.freemud.entities.vo.QueryDeliveryDistanceResponseVo;
import cn.freemud.entities.vo.ShoppingCartGoodsResponseVo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.delivery.DeliveryService;
import cn.freemud.service.store.StoreBaseApiClient;
import com.alibaba.fastjson.JSON;
import cn.freemud.service.thirdparty.ConsoleApiClient;
import cn.freemud.service.thirdparty.DeliveryFeiginClient;
import cn.freemud.utils.LocationUtil;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.membercenter.request.QueryReceiveAddressRequest;
import com.freemud.application.sdk.api.membercenter.response.QueryReceiveAddressResponse;
import com.freemud.application.sdk.api.membercenter.service.MemberCenterService;
import com.freemud.application.sdk.api.storecenter.request.QueryDeliveryRequest;
import com.freemud.application.sdk.api.storecenter.response.QueryDeliverDetailResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.math.BigDecimal;
@Service("gradDeliveryService")
public class GradDeliveryServiceImpl extends AbstractDeliveryServiceImpl implements DeliveryService {
@Autowired
private MemberCenterService memberCenterService;
@Autowired
private StoreCenterService storeCenterService;
private DeliveryFeiginClient deliveryFeiginClient;
@Autowired
private StoreBaseApiClient storeBaseApiClient;
private ConsoleApiClient consoleApiClient;
@Override
public Long calculateDeliveryAmount(String receiveId, String partnerId, String storeId, ShoppingCartGoodsResponseVo shoppingCartGoodsResponseVo) {
String trackingNo = LogThreadLocal.getTrackingNo();
QueryReceiveAddressRequest queryReceive = new QueryReceiveAddressRequest(receiveId, partnerId);
//查询会员收获地址经纬度
com.freemud.application.sdk.api.base.BaseResponse<QueryReceiveAddressResponse> queryReceiveAddressResponse = memberCenterService.queryReceiveAddressById(queryReceive, trackingNo);
......@@ -60,63 +53,35 @@ public class GradDeliveryServiceImpl extends AbstractDeliveryServiceImpl impleme
throw new ServiceException(ResponseResult.USER_GETRECEIVEADDRESS_ERROR);
}
// fisherman 新配送费计算 调用门店接口
StoreCBaseResponseDto deliveryDataMsg = getDeliveryDataMsg(queryReceiveAddressResponse.getData().getLatitude(),
DeliveryDto deliveryDataMsg = getDeliveryDataMsg(queryReceiveAddressResponse.getData().getLatitude(),
queryReceiveAddressResponse.getData().getLongitude(),
partnerId,
storeId);
if (Objects.isNull(deliveryDataMsg.getDeliveryAmount())) {
throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
}
shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(deliveryDataMsg.getDeliveryFeeZeroReason() != null ? deliveryDataMsg.getDeliveryFeeZeroReason() : 0);
return deliveryDataMsg.getDeliveryAmount();
// // 查询运费详情
// QueryDeliveryRequest queryDeliveryRequest = new QueryDeliveryRequest();
// queryDeliveryRequest.setPartnerId(partnerId);
// queryDeliveryRequest.setStoreCode(storeId);
// queryDeliveryRequest.setUserLatitude(queryReceiveAddressResponse.getData().getLatitude());
// queryDeliveryRequest.setUserLongitude(queryReceiveAddressResponse.getData().getLongitude());
// com.freemud.application.sdk.api.base.BaseResponse<QueryDeliverDetailResponse> queryDeliverDetailResponse = storeCenterService.queryDeliverDetail(queryDeliveryRequest, trackingNo);
// if (queryDeliverDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(queryDeliverDetailResponse.getCode()) || queryDeliverDetailResponse.getData() == null) {
// throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
// }
// if(queryDeliverDetailResponse.getData().getDeliveryAmount() == null) {
// throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
// }
// shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(queryDeliverDetailResponse.getData().getDeliveryFeeZeroReason() != null ? queryDeliverDetailResponse.getData().getDeliveryFeeZeroReason() : 0);
//
// return queryDeliverDetailResponse.getData().getDeliveryAmount();
if (null != shoppingCartGoodsResponseVo) shoppingCartGoodsResponseVo.setDeliveryFeeZeroReason(deliveryDataMsg.deliveryFeeZeroReason);
return deliveryDataMsg.deliveryAmount;
}
@Override
public Long calculateDeliveryAmount(String receiveId, String partnerId, String storeId) {
return this.calculateDeliveryAmount(receiveId, partnerId, storeId, null);
}
String trackingNo = LogThreadLocal.getTrackingNo();
QueryReceiveAddressRequest queryReceive = new QueryReceiveAddressRequest(receiveId, partnerId);
//查询会员收获地址经纬度
com.freemud.application.sdk.api.base.BaseResponse<QueryReceiveAddressResponse> queryReceiveAddressResponse = memberCenterService.queryReceiveAddressById(queryReceive, trackingNo);
if (!ResponseResult.SUCCESS.getCode().equals(queryReceiveAddressResponse.getCode()) || queryReceiveAddressResponse.getData() == null) {
throw new ServiceException(ResponseResult.USER_GETRECEIVEADDRESS_ERROR);
}
// 查询运费详情
QueryDeliveryRequest queryDeliveryRequest = new QueryDeliveryRequest();
queryDeliveryRequest.setPartnerId(partnerId);
queryDeliveryRequest.setStoreCode(storeId);
queryDeliveryRequest.setUserLatitude(queryReceiveAddressResponse.getData().getLatitude());
queryDeliveryRequest.setUserLongitude(queryReceiveAddressResponse.getData().getLongitude());
com.freemud.application.sdk.api.base.BaseResponse<QueryDeliverDetailResponse> queryDeliverDetailResponse = storeCenterService.queryDeliverDetail(queryDeliveryRequest, trackingNo);
if (queryDeliverDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(queryDeliverDetailResponse.getCode()) || queryDeliverDetailResponse.getData() == null) {
throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
class DeliveryDto {
/**
* 配送费
*/
Long deliveryAmount;
/**
* 配送费为零的原因:0:正常,1:超出配送范围
*/
Integer deliveryFeeZeroReason;
DeliveryDto(Long amount, Integer reason) {
deliveryAmount = amount;
deliveryFeeZeroReason = reason;
}
if(queryDeliverDetailResponse.getData().getDeliveryAmount() == null) {
throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
}
return queryDeliverDetailResponse.getData().getDeliveryAmount();
}
/**
* 获取 配送费 及预计送达时间接口
* @param userLat 用户纬度
......@@ -125,7 +90,7 @@ public class GradDeliveryServiceImpl extends AbstractDeliveryServiceImpl impleme
* @param storeCode 门店号
* @return
*/
private StoreCBaseResponseDto getDeliveryDataMsg(String userLat,
private DeliveryDto getDeliveryDataMsg(String userLat,
String userLong,
String partnerId,
String storeCode) {
......@@ -136,19 +101,112 @@ public class GradDeliveryServiceImpl extends AbstractDeliveryServiceImpl impleme
if (check) {
throw new ServiceException(ResponseResult.PARAMETER_MISSING);
}
// 调用门店接口 获取时间 Fisherman
GetEstimateDeliveryRequest request = GetEstimateDeliveryRequest.builder().latitude(userLat).longitude(userLong).build();
request.setPartnerId(partnerId);
request.setStoreCode(storeCode);
StoreCBaseResponse<StoreCBaseResponseDto> responseDto = storeBaseApiClient.queryDeliverDetail(request);
// 查询门店相关信息
GetStoreMixRequest query = GetStoreMixRequest.builder()
.partnerId(partnerId)
.storeCode(storeCode)
.query(QueryFlag.builder().queryStoreInfo(true).queryDeliveryInfo(true).build())
.build();
ConsoleResponseDTO<BizDTO> responseDto = consoleApiClient.getStoreMix(query);
if (responseDto == null) {
throw new ServiceException(ResponseResult.SYSTEM_BUSINESS_ERROR);
}
if(!ResponseResult.SUCCESS.getCode().equals(responseDto.getCode()) || responseDto.getResult() == null){
if(!ResponseResult.SUCCESS.getCode().equals(responseDto.getStatusCode()) || responseDto.getBizVO() == null){
throw new ServiceException(ResponseResult.STORE_QUERYEXPECTARRIVETIME);
}
return responseDto.getResult();
StoreInfoDTO storeInfo = responseDto.getBizVO().getStoreInfo();
DeliveryInfoDTO deliveryInfo = responseDto.getBizVO().getDeliveryInfo();
if (null == storeInfo || null == deliveryInfo || org.apache.commons.lang3.StringUtils.isAnyEmpty(storeInfo.getLatitude(), storeInfo.getLongitude())) {
throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
}
Long amount = calcDeliveryAmount(storeInfo, deliveryInfo, userLong, userLat);
if (amount < 0) {
return new DeliveryDto(0L, 1);
} else {
return new DeliveryDto(amount, 0);
}
}
/**
* 校验地址是否在门店配送范围内
*
* @param storeInfo
* @param deliveryInfo
* @param userLongitude
* @param userLatitude
* @return
*/
private boolean isDeliveryInclude(StoreInfoDTO storeInfo, DeliveryInfoDTO deliveryInfo, String userLongitude, String userLatitude) {
if (null == deliveryInfo) return false;
Integer scopeConfig = deliveryInfo.getScopeConfig();
// 配送范围绘制方式: 1-自定义 2-半径
if ("2".equals(scopeConfig)) {
if (deliveryInfo.getDeliveryRadius() == null || deliveryInfo.getDeliveryRadius() <= 0) {
throw new ServiceException(ResponseResult.STORE_DELIVERY_AMOUNT_ERROR);
}
//用户收货地址距离门店距离 单位米
double distance = LocationUtil.getDistance(Double.parseDouble(storeInfo.getLatitude()), Double.parseDouble(storeInfo.getLongitude()),
Double.parseDouble(userLatitude), Double.parseDouble(userLongitude));
if (distance > deliveryInfo.getDeliveryRadius().doubleValue()) {
return false;
}
} else if (!LocationUtil.gpsIsInclude(userLongitude, userLatitude, storeInfo.getDistributionScope())) {
// 超出配送范围
return true;
}
return true;
}
/**
* 计算配送费 (超出配送范围 返回-1)
*
* @param storeInfo
* @param deliveryInfo
* @param userLongitude 用户地址经度
* @param userLatitude 用户地址纬度
* @return
*/
public Long calcDeliveryAmount(StoreInfoDTO storeInfo, DeliveryInfoDTO deliveryInfo, String userLongitude, String userLatitude) {
if (! this.isDeliveryInclude(storeInfo, deliveryInfo, userLongitude, userLatitude)) {
//超出配送范围, 配送费设置为 -1
return -1L;
}
//用户收货地址距离门店距离 单位米 如果门店没有设置阶层配送费,配送费默认=基础配送费
if (deliveryInfo.getAddRange() == null || Integer.parseInt(deliveryInfo.getAddRange()) <= 0) {
return deliveryInfo.getDeliveryAmount() == null ? 0L : Long.parseLong(deliveryInfo.getDeliveryAmount() + "");
}
if (deliveryInfo.getAddRangeAmount() == null || deliveryInfo.getAddRangeAmount() <= 0) {
return deliveryInfo.getDeliveryAmount() == null ? 0L : Long.parseLong(deliveryInfo.getDeliveryAmount() + "");
}
// 查询外卖的骑行距离
Integer riderDistance;
try {
QueryDeliveryDistanceRequest queryDistance = new QueryDeliveryDistanceRequest(Double.parseDouble(storeInfo.getLatitude()), Double.parseDouble(storeInfo.getLongitude()), Double.parseDouble(userLatitude), Double.parseDouble(userLongitude));
QueryDeliveryDistanceResponseVo distanceResp = deliveryFeiginClient.queryDeliveryDistance(queryDistance);
riderDistance = distanceResp.getData().getDistance();
} catch (Exception e) {
Double lineDistance = LocationUtil.getDistance(Double.parseDouble(storeInfo.getLatitude()), Double.parseDouble(storeInfo.getLongitude()),
Double.parseDouble(userLatitude), Double.parseDouble(userLongitude));
riderDistance = lineDistance.intValue();
}
Long defaultDeliveryRange = deliveryInfo.getDeliveryRange() == null ? 0 : Long.parseLong(deliveryInfo.getDeliveryRange());
Long deliveryAmount = deliveryInfo.getDeliveryAmount() == null ? 0 : Long.parseLong(deliveryInfo.getDeliveryAmount() + "");
Long addRangeCount = deliveryInfo.getAddRange() == null ? 0 : Long.parseLong(deliveryInfo.getAddRange());
Long addRangeAmount = deliveryInfo.getAddRangeAmount() == null ? 0 : Long.parseLong(deliveryInfo.getAddRangeAmount() + "");
if (new BigDecimal(riderDistance).compareTo(new BigDecimal(defaultDeliveryRange)) <= 0) {
return deliveryAmount;
} else {
//计算实际配送费
BigDecimal extraAmount = (new BigDecimal(riderDistance).subtract(new BigDecimal(defaultDeliveryRange)))
.divide(new BigDecimal(addRangeCount), 0, BigDecimal.ROUND_UP)
.multiply(new BigDecimal(addRangeAmount));
BigDecimal realAmount = new BigDecimal(deliveryAmount).add(extraAmount);
return realAmount.longValue();
}
}
}
package cn.freemud.service.store;
import cn.freemud.entities.dto.store.StoreCBaseResponse;
import cn.freemud.entities.dto.store.StoreCBaseResponseDto;
import cn.freemud.entities.dto.store.StoreInfoRequestDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author : xh.Z
* @email : fisherman0510@163.com
* @Date : 2021/6/4 下午2:04
* @description : 门店基础服务
*/
@FeignClient(name = "store-menu-application-service")
@RequestMapping(value = "/store", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public interface StoreBaseApiClient {
@PostMapping(value = "/delivery/calcDeliveryData")
StoreCBaseResponse<StoreCBaseResponseDto> queryDeliverDetail(@RequestBody StoreInfoRequestDto request);
}
......@@ -20,7 +20,7 @@ import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient("CONSOLE-API")
@FeignClient(value = "CONSOLE-API", url = "${saas.storeclient.feign.url:}")
@RequestMapping(produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public interface ConsoleApiClient {
......
package cn.freemud.utils;
import org.apache.commons.lang.StringUtils;
import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class LocationUtil {
private static double EARTH_RADIUS = 6378.137;
private static double EARTH_RADIUS_NEW = 6378137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* 通过经纬度获取距离(单位:米)
*
* @param lat1
* @param lng1
* @param lat2
* @param lng2
* @return
*/
public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.asin(Math.sqrt(
Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS_NEW;
return s;
}
/// <summary>
/// 给定的经度1,纬度1;经度2,纬度2. 计算2个经纬度之间的距离。
/// </summary>
/// <param name="lat1">经度1</param>
/// <param name="lon1">纬度1</param>
/// <param name="lat2">经度2</param>
/// <param name="lon2">纬度2</param>
/// <returns>距离(公里、千米)</returns>
public static double distance(double lat1, double lon1, double lat2, double lon2) {
//用haversine公式计算球面两点间的距离。
//经纬度转换成弧度
lat1 = convertDegreesToRadians(lat1);
lon1 = convertDegreesToRadians(lon1);
lat2 = convertDegreesToRadians(lat2);
lon2 = convertDegreesToRadians(lon2);
//差值
double vLon = Math.abs(lon1 - lon2);
double vLat = Math.abs(lat1 - lat2);
//h is the great circle distance in radians, great circle就是一个球体上的切面,它的圆心即是球心的一个周长最大的圆。
double h = haverSin(vLat) + Math.cos(lat1) * Math.cos(lat2) * haverSin(vLon);
double distance = 2 * EARTH_RADIUS * Math.asin(Math.sqrt(h));
//返回的距离保留5位小数(思舍五入)
//BigDecimal bg = new BigDecimal(distance);
BigDecimal bg = BigDecimal.valueOf(distance);
distance = bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
return distance;
}
public static double haverSin(double theta) {
double v = Math.sin(theta / 2);
return v * v;
}
/// <summary>
/// 将角度换算为弧度。
/// </summary>
/// <param name="degrees">角度</param>
/// <returns>弧度</returns>
public static double convertDegreesToRadians(double degrees) {
return degrees * Math.PI / 180;
}
public static double ConvertRadiansToDegrees(double radian) {
return radian * 180.0 / Math.PI;
}
/**
* 判断2个经纬度的距离是否在半径范围内
*
* @param orgLongitude 门店经度
* @param orgLatitude 门店纬度
* @param longitude
* @param latitude
* @param radius 半径(米)
* @return
*/
public static boolean checkDistance(String orgLongitude, String orgLatitude, String longitude, String latitude, String radius) {
double distance = LocationUtil.distance(Double.parseDouble(orgLatitude), Double.parseDouble(orgLongitude),
Double.parseDouble(latitude), Double.parseDouble(longitude));
if (StringUtils.isNotEmpty(radius)) {
if (distance * 1000 <= Double.parseDouble(radius)) {
return true;
}
}
return false;
}
/**
* 获取坐标是否在多边形范围里
*
* @param longitude
* @param latitude
* @param DistributionScopeforshow 多边形点集合 [[113.8524341583252,22.56028129823027],[113.8524341583252,22.56028129823027],...]
* @return
*/
public static boolean gpsIsInclude(String longitude, String latitude, String DistributionScopeforshow) {
if (StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude)) {
return false;
}
Point2D.Double point = new Point2D.Double(Double.parseDouble(longitude), Double.parseDouble(latitude));
List<Point2D.Double> pts = new ArrayList<Point2D.Double>();
if (null != DistributionScopeforshow && DistributionScopeforshow.length() > 0) {
DistributionScopeforshow = DistributionScopeforshow.replaceAll("\\[", "").replaceAll("\\]", "");
String[] strDis = DistributionScopeforshow.split(",");
if (strDis.length > 0) {
for (int i = 0; i < strDis.length; i++) {
pts.add(new Point2D.Double(Double.parseDouble(strDis[i]), Double.parseDouble(strDis[i + 1])));
i++;
}
}
//Map map = new HashMap();
//map.put("isInclude", "true");
//map.put("isInclude", "false");
return isPtInPoly(point, pts);
}
return false;
}
/**
* 判断点是否在多边形内
*
* @param point 检测点
* @param pts 多边形的顶点
* @return 点在多边形内返回true, 否则返回false
*/
public static boolean isPtInPoly(Point2D.Double point, List<Point2D.Double> pts) {
int N = pts.size();
boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0;// cross points count of x
double precision = 2e-10; // 浮点类型计算时候与0比较时候的容差
Point2D.Double p1, p2;// neighbour bound vertices
Point2D.Double p = point; // 当前点
p1 = pts.get(0);// left vertex
for (int i = 1; i <= N; ++i) {// check all rays
if (p.equals(p1)) {
return boundOrVertex;// p is an vertex
}
p2 = pts.get(i % N);// right vertex
if (p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)) {// ray is outside of our interests
p1 = p2;
continue;// next ray left point
}
if (p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)) {// ray is crossing over by the algorithm
// (common part of)
if (p.y <= Math.max(p1.y, p2.y)) {// x is before of ray
if (p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)) {// overlies on a horizontal ray
return boundOrVertex;
}
if (p1.y == p2.y) {// ray is vertical
if (p1.y == p.y) {// overlies on a vertical ray
return boundOrVertex;
} else {// before ray
++intersectCount;
}
} else {// cross point on the left side
double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;// cross point of y
if (Math.abs(p.y - xinters) < precision) {// overlies on a ray
return boundOrVertex;
}
if (p.y < xinters) {// before ray
++intersectCount;
}
}
}
} else {// special case when ray is crossing through the vertex
if (p.x == p2.x && p.y <= p2.y) {// p crossing over p2
Point2D.Double p3 = pts.get((i + 1) % N); // next vertex
if (p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)) {// p.x lies between p1.x & p3.x
++intersectCount;
} else {
intersectCount += 2;
}
}
}
p1 = p2;// next ray left point
}
if (intersectCount % 2 == 0) {// 偶数在多边形外
return false;
} else { // 奇数在多边形内
return true;
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment