如何调用百度地图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配合使用stringSN存在时必填
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、示例代码(支持多种语言)

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

### 如何在Java调用地图API #### 使用高德地图API进行地理编码 为了通过Java程序访问并利用高德地图的服务,开发者可以采用HTTP请求的方式向指定接口发送参数获取所需数据。具体来说,在处理地址解析成地理位置的任务时,即所谓的“正向地理编码”,可以通过构建URL字符串的形式传递待查询的位置描述给服务器。 创建一个新的`HttpURLConnection`实例用于发起GET请求至目标网址,并设置必要的连接属性以便于接收JSON格式返回的结果集[^1]: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GaoDeMapApiExample { private static final String API_KEY = "您的API密钥"; public static void main(String[] args) throws Exception { StringBuilder response = new StringBuilder(); URL url = new URL("https://restapi.amap.com/v3/geocode/geo?address=北京市朝阳区阜通东街6号&key=" + API_KEY); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null){ response.append(line); } rd.close(); System.out.println(response.toString()); } } ``` 这段代码展示了怎样构造一个简单的网络请求去取得由文字表述的地名对应的经度纬度信息。注意这里的`API_KEY`应该替换为自己申请得到的有效秘钥[^2]。 对于更复杂的场景比如路线规划,则可能涉及到POST方法以及更多的输入项如起点终点坐标等。此时除了调整请求方式外还需要关注响应体内的结构变化,例如提取路径上的节点位置[^3]。
评论 67
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你才是臭弟弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值