java中各种距离换算

2020-09-29 09:44:40 浏览数 (1)

获取两点之间的距离

代码语言:javascript复制
public class LocationUtils {
    /**
     * 赤道半径
     */
    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * Description : 通过经纬度获取距离(单位:米)
     * Group :
     *
     * @param origin      出发点
     * @param destination 目的地
     * @return double
     */
    public static double getDistance(String origin, String destination) {
        if (origin == null) {
            log.error("出发点 经纬度不可以为空!");
            return 0;
        }
        if (destination == null) {
            log.error("目的地 经纬度不可以为空!");
            return 0;
        }
        String[] temp = origin.split(",");
        String[] temp2 = destination.split(",");

        double radLat1 = rad(Double.parseDouble(temp[1]));
        double radLat2 = rad(Double.parseDouble(temp2[1]));
        double a = radLat1 - radLat2;
        double b = rad(Double.parseDouble(temp[0])) - rad(Double.parseDouble(temp2[0]));
        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;
        // 保留两位小数
        s = Math.round(s * 100d) / 100d;
        s = s * 1000;
        return s;
    }

    /**
     * Description : 通过经纬度获取距离(单位:米)
     * Group :
     *
     * @param originLon      出发点经度
     * @param originLat      出发点纬度
     * @param destinationLon 目的地经度
     * @param destinationLat 目的地纬度
     * @return double
     */
    public static double getDistance(String originLon, String originLat, String destinationLon, String destinationLat) {
        if (StringUtil.isEmpty(originLon)) {
            log.error("出发点 经度不可以为空!");
            return 0;
        }
        if (StringUtil.isEmpty(originLat)) {
            log.error("出发点 纬度不可以为空!");
            return 0;
        }
        if (StringUtil.isEmpty(destinationLon)) {
            log.error("目的地 经度不可以为空!");
            return 0;
        }
        if (StringUtil.isEmpty(destinationLat)) {
            log.error("目的地 纬度不可以为空!");
            return 0;
        }

        double radLat1 = rad(Double.parseDouble(originLat));
        double radLat2 = rad(Double.parseDouble(destinationLat));
        double a = radLat1 - radLat2;
        double b = rad(Double.parseDouble(originLon)) - rad(Double.parseDouble(destinationLon));
        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;
        // 保留两位小数
        s = Math.round(s * 100d) / 100d;
        s = s * 1000;
        return s;
    }
}

根据位置获取经纬度

代码语言:javascript复制
/**
     * Description : 地理编码 获取详细地址的经纬度
     * Group :
     *
     * @param address     详细地址
     * @param currentCity 市
     * @return java.lang.String
     */
    public static String getLocationGeocodeGeo(String address, String currentCity) {

        Map<String, String> querys = new HashMap<String, String>();
        querys.put("address", address);
        querys.put("city", currentCity);
        querys.put("key", APP_CODE_GAODE); // APP_CODE_GAODE 高德秘钥

        try {
            HttpResponse response = HttpUtils.doGet(QUERY_KEYWD_URL_GAODE_GEOCODE_GEO, "", "GET", null, querys);//QUERY_KEYWD_URL_GAODE_GEOCODE_GEO 高德-地址获取唯一经纬度 : http://restapi.amap.com/v3/geocode/geo
            String resData = EntityUtils.toString(response.getEntity());
            JSONObject json = JSONObject.parseObject(resData);
            if (json == null) {
                logger.error("列表信息获取失败,关键字:"   address   "城市:"   currentCity);
                return null;
            }
            String status = json.getString("status");
            if ("1".equals(status)) {
                JSONArray jsonArray = json.getJSONArray("geocodes");
                if (jsonArray == null || jsonArray.size() == 0) {
                    return null;
                }
                JSONObject object = jsonArray.getJSONObject(0);

                return object.getString("location");
            } else {
                return null;
            }
        } catch (Exception e1) {
            logger.error("调用接口失败!"   e1.getMessage());
            return null;
        }
    }
    
    public static void main(String[] args) {
		//根据位置获取经纬度
        String origin = getLocationGeocodeGeo("天津市水上公园", "天津市");
		//根据位置获取经纬度
        String destination = getLocationGeocodeGeo("天津市南开区花园路470号", "天津市");
        System.out.println(destination);
		//根据经纬度获取两点之间的距离(经度纬度)
        double distance = LocationUtils.getDistance(origin.split(",")[0], origin.split(",")[1], destination.split(",")[0], destination.split(",")[1]);
        //不足一千米用 m 显示
        if (distance < 1000) {
            System.out.println("两地距离: "   new Double(distance).intValue()   "M");
        } else {
            System.out.println("两地距离: "   distance / 1000   "KM");
        }
		//根据经纬度获取两点之间的距离(经纬度用,分隔)
        double distance2 = LocationUtils.getDistance(origin, destination);
        System.out.println("两地距离2: "   distance2 / 1000   "KM");
 
        double dis = LocationUtils.getDistance("120.12026","30.33761","120.124597","30.323823");
        System.out.println("dis  " dis);
    }

根据经纬度获取地理位置

代码语言:javascript复制
   public String getAdd(String lat, String lng) {
        Map map = bd_encrypt(Double.parseDouble(lat), Double.parseDouble(lng));
        Object lat1 = map.get("lat");
        Object log1 = map.get("log");
        String urlString = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=你的秘钥="   lat1   ","   log1;
        String s = doPost(urlString, null);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String result = jsonObject.getString("result");
        JSONObject jsonObject1 = JSONObject.parseObject(result);
        JSONObject addressComponent = JSONObject.parseObject(jsonObject1.getString("addressComponent"));
        String city = addressComponent.getString("city");
        return city;
    }
//获取位置调用
 public Map bd_encrypt(double gg_lat, double gg_lng) {
        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        double bd_lat, bd_lng;
        double x = gg_lng, y = gg_lat;
        double z = Math.sqrt(x * x   y * y)   0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x)   0.000003 * Math.cos(x * x_pi);
        bd_lng = z * Math.cos(theta)   0.0065;
        bd_lat = z * Math.sin(theta)   0.006;
        Map map = new HashMap();
        map.put("log", bd_lng);
        map.put("lat", bd_lat);
        return map;
    }

根据ip获取当前地理位置

代码语言:javascript复制
//获取本机ip
	public static String getPublicIP() {    
    String ip = "";    
    org.jsoup.nodes.Document doc = null; 
    Connection con = null;    
    con = Jsoup.connect("http://www.ip138.com/ip2city.asp").timeout(10000);
    try { 
	doc = con.get();    
        // 获得包含本机ip的文本串:您的IP是:[xxx.xxx.xxx.xxx] 
	org.jsoup.select.Elements els = doc.body().select("center");    
	    for (org.jsoup.nodes.Element el : els) {    
	    ip = el.text();     
	}    
	// 从文本串过滤出ip,用正则表达式将非数字和.替换成空串""    
	ip = ip.replaceAll("[^0-9.]", "");    
    } catch (IOException e) {    
	e.printStackTrace();    
    }    
    return ip;    
	}
	
//将字符拼成字符串	
	
private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
}


//将URL解析成JSON对象
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            //关闭输入流
            is.close();
        }
}
//获取当前地址的信息
public static String getAddrName() throws JSONException, IOException{
        //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
        JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg&ip=" getPublicIP());
        /* 获取到的json对象:
         *         {"address":"CN|河北|保定|None|UNICOM|0|0",
         *        "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307},
         *        "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}},
         *        "status":0}
        */
     //这里我们可以输出json看一下具体格式
    System.out.println(json.toString());
 
        JSONObject content=json.getJSONObject("content");              //获取json对象里的content对象
        JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail
        String city=addr_detail.get("city").toString();                //获取市名,可以根据具体需求更改,如果需要获取省份的名字,可以把“city”改成“province”...
        return city;
}

根据经纬度获取两点之间的距离

代码语言:javascript复制
			<dependency>
              <groupId>org.gavaghan</groupId>
              <artifactId>geodesy</artifactId>   //---------导入的jar
              <version>1.1.3</version>
			</dependency>
代码语言:javascript复制
public class test0 {
    public static void main(String[] args){
        // //121.717594,31.12055    121.817629,31.090867
		//lat  31.12055  纬度
		//lng  121.717594  精度
        GlobalCoordinates source = new GlobalCoordinates(31.12055, 121.717594);
        GlobalCoordinates target = new GlobalCoordinates(31.090867, 121.817629);
 
        double meter1 = getDistanceMeter(source, target, Ellipsoid.Sphere);
        double meter2 = getDistanceMeter(source, target, Ellipsoid.WGS84);
 
        System.out.println("Sphere坐标系计算结果:" meter1   "米");
        System.out.println("WGS84坐标系计算结果:" meter2   "米");
    }
 
    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid){
        //创建GeodeticCalculator,调用计算方法,传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
 
        return geoCurve.getEllipsoidalDistance();
    }
}
ip

0 人点赞