如何调用百度地图API

 

前言

要调用百度地图API,步骤操作如下

  1. 注册并创建一个API密钥。您可以在百度地图API控制台上创建您的密钥。
  2. 选择要使用的API服务。百度地图API提供了多种服务,包括地图展示、路线规划、地点搜索、实时交通等。您可以在百度地图API控制台上查看所有可用的服务。
  3. 在调用API时,将API密钥添加到请求中。

官网:百度地图开放平台 | 百度地图API SDK

1、了解地图开放平台

 可以看到开发文档支持多种类型,前端到后台等等。百度地图API提供了多种服务,包括地图展示、路线规划、地点搜索、鹰眼轨迹,定位,实时交通等。

 2、创建百度地图AK

2.1、控制台→应用管理→我的应用→创建应用

2.2、创建应用名字

 为什么高级是灰色选不了,是因为高级服务是需要付费的。

2.4、IP白名单设置

 2.5、查看AK

3、JAVA调用百度地图

3.1、地点检索

3.1.1、调用百度Api 

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Map;


public class BaiduApiController {

    public static void main(String[] args) {
        String ak = "自己AK";
        String address = "天津之眼摩天轮";
//        String httpUrl = "http://api.map.baidu.com/geocoding/v3/?address="+address+ ak;
        String httpUrl = "http://api.map.baidu.com/geocoding/v3/?address="+address+"&output=json&ak=" + ak;
        StringBuilder json = new StringBuilder();
        try {
            URL url = new URL(httpUrl);
            URLConnection urlConnection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        System.out.println(json.toString());
        String data = json.toString();
        if (data != null && !"".equals(data)) {
            Map map = JSON.parseObject(data, Map.class);
            if ("0".equals(map.getOrDefault("status", "500").toString())) {
                Map childMap = (Map) map.get("result");
                Map posMap = (Map) childMap.get("location");
                double lng = Double.parseDouble(posMap.getOrDefault("lng", "0").toString()); // 经度
                double lat = Double.parseDouble(posMap.getOrDefault("lat", "0").toString()); // 纬度
                DecimalFormat df = new DecimalFormat("#.######");
                String lngStr = df.format(lng);
                String latStr = df.format(lat);
                String result = lngStr + "," + latStr;
                System.out.println("坐标"+result);
            }
        }
    }
}

3.1.2、查看结果

3.1.3、验证

3.2、计算两点之间距离

3.2.1、调用百度Api 

mport com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Map;

/**
 * 百度地图操作工具类
 */
public class BaiduApiUtils {
    public static void main(String[] args) {
        String origin = getCoordinate("天津之眼摩天轮");
        String destination = getCoordinate("北京市百度大厦");
        Double distance = getDistance(origin, destination);
        System.out.println("订单距离:" + distance + "米");
        Integer time = getTime(origin, destination);
        System.out.println("线路耗时" + time + "秒");
    }

    private static String AK = "自己AK";

    /**
     * 调用百度地图地理编码服务接口,根据地址获取坐标(经度、纬度)
     *
     * @param address
     * @return
     */
    public static String getCoordinate(String address) {
        String httpUrl = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + AK;
        String json = loadJSON(httpUrl);
        Map map = JSON.parseObject(json, Map.class);

        String status = map.get("status").toString();
        if (status.equals("0")) {
            //返回结果成功,能够正常解析地址信息
            Map result = (Map) map.get("result");
            Map location = (Map) result.get("location");
            String lng = location.get("lng").toString();
            String lat = location.get("lat").toString();

            DecimalFormat df = new DecimalFormat("#.######");
            String lngStr = df.format(Double.parseDouble(lng));
            String latStr = df.format(Double.parseDouble(lat));
            String r = latStr + "," + lngStr;
            return r;
        }

        return null;
    }

    /**
     * 调用百度地图驾车路线规划服务接口,根据寄件人地址和收件人地址坐标计算订单距离
     *
     * @param origin
     * @param destination
     * @return
     */
    public static Double getDistance(String origin, String destination) {
        String httpUrl = "http://api.map.baidu.com/directionlite/v1/driving?origin="
                + origin + "&destination="
                + destination + "&ak=" + AK;

        String json = loadJSON(httpUrl);

        Map map = JSON.parseObject(json, Map.class);
        if ("0".equals(map.getOrDefault("status", "500").toString())) {
            Map childMap = (Map) map.get("result");
            JSONArray jsonArray = (JSONArray) childMap.get("routes");
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
            double distance = Double.parseDouble(jsonObject.get("distance") == null ? "0" : jsonObject.get("distance").toString());
            return distance;
        }

        return null;
    }

    /**
     * 调用百度地图驾车路线规划服务接口,根据寄件人地址和收件人地址坐标计算订单距离
     *
     * @param origin
     * @param destination
     * @return
     */
    public static Integer getTime(String origin, String destination) {
        String httpUrl = "http://api.map.baidu.com/directionlite/v1/driving?origin="
                + origin + "&destination="
                + destination + "&ak=" + AK;

        String json = loadJSON(httpUrl);

        Map map = JSON.parseObject(json, Map.class);
        if ("0".equals(map.getOrDefault("status", "500").toString())) {
            Map childMap = (Map) map.get("result");
            JSONArray jsonArray = (JSONArray) childMap.get("routes");
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
            int time = Integer.parseInt(jsonObject.get("duration") == null ? "0" : jsonObject.get("duration").toString());
            return time;
        }

        return null;
    }

    /**
     * 调用服务接口,返回百度地图服务端的结果
     *
     * @param httpUrl
     * @return
     */
    public static String loadJSON(String httpUrl) {
        StringBuilder json = new StringBuilder();
        try {
            URL url = new URL(httpUrl);
            URLConnection urlConnection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        System.out.println(json.toString());
        return json.toString();
    }
}

3.2.2、查看结果

3.3、地点输入提示

3.3.1、调用百度Api 

/**
 * 选择了ak或使用IP白名单校验:
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

public class SearchHttpAK {

    public static String URL = "https://api.map.baidu.com/place/v2/suggestion?";

    public static String AK = "自己AK";

    public static void main(String[] args) throws Exception {

        SearchHttpAK snCal = new SearchHttpAK();

        Map params = new LinkedHashMap<String, String>();
        params.put("query", "天安门");
        params.put("region", "北京");
        params.put("city_limit", "true");
        params.put("output", "json");
        params.put("ak", AK);


        snCal.requestGetAK(URL, params);
    }

    /**
     * 默认ak
     * 选择了ak,使用IP白名单校验:
     * 根据您选择的AK以为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP,请设置为公网IP,否则将请求失败
     * 请在IP地址为0.0.0.0/0 外网IP的计算发起请求,否则将请求失败
     */
    public void requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        System.out.println("AK: " + buffer.toString());
    }
}

 3.3.2、查看结果

4、接口说明

4.1、接口文档说明

  • 开发文档有很多案例类型,可根据项目业务需求进行选择性调用。

4.2、请求参数 

  • 有些参数是必填就比如开发者密钥AK ,这个参数没有都请求不到数据。
字段名称 字段含义 字段类型 必填 备注
ak

开发者密钥,AK申请

string
origin 起点 double,double 起点经纬度,格式为:纬度,经度;小数点后不超过6位,40.056878,116.30815
destination 终点 double,double 终点经纬度,格式为:纬度,经度;小数点后不超过6位,40.056878,116.30815
origin_uid 起点uid,POI 的 uid(在已知起点POI 的 uid 情况下,请尽量填写uid,将提升路线规划的准确性) string
destination_uid 终点uid,POI 的 uid(在已知终点POI 的 uid 情况下,请尽量填写uid,将提升路线规划的准确性) string
riding_type 骑行类型 string

默认0
0:普通自行车
1:电动自行车

coord_type 输入坐标类型 string

默认bd09ll
允许的值为:
bd09ll:百度经纬度坐标
bd09mc:百度墨卡托坐标
gcj02:国测局加密坐标
wgs84:gps设备获取的坐标

ret_coordtype 输出坐标类型 string

返回值的坐标类型,默认为百度经纬度坐标:bd09ll
可选值:
bd09ll:百度经纬度坐标
gcj02:国测局加密坐标

sn

用户的权限签名,当AK设置为SN校验时,该参数必填SN计算方法

string
timestamp 时间戳,与SN配合使用 string SN存在时必填
steps_info

是否下发step详情
1:下发step详情
2:不下发step详情

int

 4.3、返回参数 

  • 返回的状态 ,错误码等等都写的非常详细。
字段名称 字段含义 备注
status 状态码 0:成功
1:服务内部错误
2:参数无效
7:无返回结果
message 状态码对应的信息
result 返回的结果
origin
lng 起点经度
lat 起点纬度
destination
lng 终点经度
lat 终点纬度
routes 返回的方案集
distance 方案距离,单位:米
duration 线路耗时,单位:秒
steps 路线分段
direction 进入道路的角度 枚举值,返回值在0-11之间的一个值,共12个枚举值,以30度递进,即每个值代表角度范围为30度;其中返回"0"代表345度到15度,以此类推,返回"11"代表315度到345度";分别代表的含义是:0-[345°-15°];1-[15°-45°];2-[45°-75°];3-[75°-105°];4-[105°-135°];5-[135°-165°];6-[165°-195°];7-[195°-225°];8-[225°-255°];9-[255°-285°];10-[285°-315°];11-[315°-345°]
turn_type 行驶转向方向 如“直行”、“左前方转弯”
distance 路段距离 单位:米
duration 路段耗时 单位:秒
name 道路名称 如:“信息路”
若道路未明或百度地图未采集到该道路名称,则返回“无名路“
instruction 路段描述
start_location
lng 分段起点经度
lat 分段起点纬度
end_location
lng 分段终点经度
lat 分段终点纬度
path 分段坐标

4.4、示例代码(支持多种语言)

总之,根据自己的业务需求去选择地图的种类,以上只是介绍服务端, 感兴趣的可以去试一下。

猜你喜欢

转载自blog.csdn.net/weixin_50002038/article/details/131211059