返回,离当前用户定位最近的点位坐标(数据库存储点位经纬度)

@Override
public Integer getDistributionCenter(LongitudeAndLatitudeRequest request) {
	double userLatitude = Double.parseDouble(request.getLat());
	double userLongitude  = Double.parseDouble(request.getLng());

	// 配送中心Id;配送中心经纬度
	HashMap hashMap = new HashMap<>();

	//配送中心筛选条件待优化
	R> dcList = remoteDistributionCenterService.getDcList();
	List data = dcList.getData();

	for (DistributionCenter datum : data) {
		Integer dcId = datum.getId();
		String lat = datum.getLat();
		String lng = datum.getLng();
		hashMap.put(dcId,new CoordinateUtil.Coordinate(Double.parseDouble(lng),Double.parseDouble(lat)));
	}
	Iterator> iterator = hashMap.entrySet().iterator();

	double minDistance = Double.MAX_VALUE;
	int minIndex = -1;
	while (iterator.hasNext()){
		Map.Entry entry = iterator.next();
		double distance = calculateDistance(userLatitude, userLongitude, entry.getValue().getLat(), entry.getValue().getLng());
		if (distance < minDistance) {
			minDistance = distance;
			minIndex = entry.getKey();
		}
	}
	return minIndex;
}

//计算2个经纬度之前的距离
public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
	double radLat1 = Math.toRadians(lat1);
	double radLat2 = Math.toRadians(lat2);
	double radLon1 = Math.toRadians(lon1);
	double radLon2 = Math.toRadians(lon2);

	double latDiff = radLat1 - radLat2;
	double lonDiff = radLon1 - radLon2;

	double a = Math.pow(Math.sin(latDiff / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(lonDiff / 2), 2);
	double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

	return 6371 * c; // 地球平均半径,单位:公里
}

你可能感兴趣的:(数据库)