高德地图WebAPI : 驾车路径规划

参考API


一个demo

获取路径规划返回结果中的两点间最短驾车距离


import java.io.BufferedReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Test2 {    

    public  static String getHttpResponse(String allConfigUrl) {
        BufferedReader in = null;
        StringBuffer result = null;
        try {
            //url请求中如果有中文,要在接收方用相应字符转码
            URI uri = new URI(allConfigUrl);
            URL url = uri.toURL();
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Content-type", "text/html");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("contentType", "utf-8");
            connection.connect();     
            result = new StringBuffer();
            //读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
         return result.toString();   
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

    /*
     * 高德地图WebAPI : 驾车路径规划
     */
    public static String distance(String origins,String destination) { 
        int strategy = 2;//strategy=2距离优先,一共有九种查询模式,详情查看API
        String url = "http://restapi.amap.com/v3/direction/driving?"
                    + "origin="+origins
                    +"&destination="+destination
                    +"&strategy="+strategy
                    +"&extensions=base&key=你申请的key";
        JSONObject jsonobject = JSONObject.fromObject(getHttpResponse(url));
        System.out.println(jsonobject.toString());
        JSONArray pathArray = jsonobject.getJSONObject("route").getJSONArray("paths");
        String distanceString  = pathArray.getJSONObject(0).getString("distance");
        return distanceString;
    }

    public static void main(String[] args) {
        //格式:   经度,纬度      
        //注意:高德最多取小数点后六位
        String origin = "116.398140"+","+"26.059369";
        String destination = "116.374028"+","+"39.907586";
        String distance = distance(origin, destination);
        System.out.println(distance);
    }

}

你可能感兴趣的:(高德地图API)