高德地图计算两点间距离(java)

  • Post author:
  • Post category:java



package cn.makenova.api.v1.login;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class GaodMap {
    public static final String MAP_KEY = "6cb244f1a67c3bf042f489c2be3b76dc";


    public static void main(String[] args) {
        String startPoint="113.568824,34.807564";
        String endPoint="113.657485,34.745224";
        //59.0190199454325
        Double dis       = getDis(Double.parseDouble(startPoint.substring(startPoint.indexOf(",")+1)),
                Double.parseDouble(startPoint.substring(0,startPoint.indexOf(","))),
                Double.parseDouble(endPoint.substring(endPoint.indexOf(",")+1)),
                Double.parseDouble(endPoint.substring(0,endPoint.indexOf(","))));
        System.out.println("计算距离结果:"+dis);
        long distance = getDistance(startPoint, endPoint);
        System.out.println("api调用距离结果:"+distance);
    }

    /**
	 * 1.直接程序计算
	 */
    public static Double getDis(Double lat1,Double lon1,Double lat2,Double lon2 ){
        Double radLat1=(lat1 * Math.PI) /180;
        Double radLat2=(lat2 * Math.PI) /180;
        Double a=radLat1-radLat2;
        Double b=(lon1 * Math.PI) /180 -(lon2 * Math.PI)/180;
        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* 6378137.0;
        return s;
    }


    /**
     * 2.经纬度算出两点间距离(通过api调用计算)
     * 
	 */
    public static long getDistance(String startLonLat, String endLonLat){
        //返回起始地startAddr与目的地endAddr之间的距离,单位:米
        Long result = new Long(0);
        String queryUrl = "http://restapi.amap.com/v3/distance?key="+MAP_KEY+"&origins="+startLonLat+"&destination="+endLonLat+"&type=0";
        String queryResult = HttpUtil.get(queryUrl);
        //System.out.println(queryResult);
        JSONObject job  = JSONObject.parseObject(queryResult);
        JSONArray  ja   = job.getJSONArray("results");
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        result = Long.parseLong(jobO.get("distance").toString());
        //System.out.println("距离:"+result);
        return result;
    }

}



版权声明:本文为zhengxiaoya2017原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。