zoukankan      html  css  js  c++  java
  • 根据两点的经纬度坐标计算两个坐标点之间的直线距离

    贴代码如下:

    import java.awt.*;
    
    /**
     * @author xulin
     * @date create in 9:06 2018/11/1
     * Description 根据提供的两个国标经纬度,计算两个点之间的距离
     */
    public class DistanceConsider {
        // 地球半径
        private static double EARTH_RADIUS = 6378.137;
    
        private static double rad(double d) {
            return d * Math.PI / 180.0;
        }
    
        /**
         * @author xulin
         * date 9:09 2018/11/1
         * Description 计算距离
         * 参数传入:所在位置的坐标  目标位置的坐标
         * 一个参数的经纬之前要求使用","英文的逗号进行分隔
         * 返回: 输入的两个坐标点之间的距离  精确到小数点后两位
         */
        public static double getDistance(String location, String target) {
            int locationCount = location.indexOf(",");
            // 源地点的经度
            double lngLocation = Double.parseDouble(location.substring(0, locationCount));
            // 源地点的维度
            double latLocation = Double.parseDouble(location.substring(locationCount + 1, location.length()));
            int targetCount = target.indexOf(",");
            // 目标地点的经度
            double lngTarget = Double.parseDouble(target.substring(0, targetCount));
            // 目标地点的维度
            double latTarget = Double.parseDouble(target.substring(targetCount + 1, target.length()));
    
            double lat1 = rad(latLocation);
            double lat2 = rad(latTarget);
            double lat = lat1 - lat2;
            double lng = rad(lngLocation) - rad(lngTarget);
            double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(lat / 2), 2)
                    + Math.cos(lat1) * Math.cos(lat2)
                    * Math.pow(Math.sin(lng / 2), 2)));
            distance = distance * EARTH_RADIUS;
            distance = Math.round(distance * 10000d) / 10000d;
            distance = distance * 1000;
            return distance;
        }
    
        public static void main(String args[]) {
            String location = "116.368904, 39.923423";
            String target = "116.387271, 39.922501";
            System.out.println(getDistance(location, target));
        }
    }

    刚开始一直计算错误,是自己没有区分经纬度,地理是硬伤,谷歌的公式是对的,网上的大部分方法也是对的, 如果计算之后发现了较大的误差,记得查看经纬度是否计算反了,避免低级错误~~~~

  • 相关阅读:
    十二、curator recipes之双重屏障DoubleBarrier
    十一、curator recipes之联锁InterProcessMultiLock
    十、curator recipes之信号量InterProcessSemaphoreV2
    九、curator recipes之不可重入锁InterProcessSemaphoreMutex
    八、curator recipes之选举主节点LeaderSelector
    五、curator recipes之选举主节点Leader Latch
    ADO.net 数据库连接new SqlConnection、Open、Close、Dispose
    Java学习笔记【八、数据结构】
    Java学习笔记【七、时间、日期、数字】
    Java学习笔记【六、正则表达式】
  • 原文地址:https://www.cnblogs.com/cswxl/p/9888642.html
Copyright © 2011-2022 走看看