0
点赞
收藏
分享

微信扫一扫

Springboot 整合百度地图 API

茗越 2022-08-02 阅读 55


前言

正文

1. 创建百度账号,申请成为开发者 :


Springboot 整合百度地图 API_百度

 2. 创建应用,得到ak :


Springboot 整合百度地图 API_百度_02

3. ok,可以开始使用了 ,具体API文档可以看官方 :​​https://lbsyun.baidu.com/index.php?title=webapi/ip-api​​

Springboot 整合百度地图 API_json_03

封装好的对接实例, 我们就拿 普通IP定位作为示例:

BaiduAddressUtil.java

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

/**
* @Author JCccc
* @Description
* @Date 2021/7/14 9:34
*/
@Component
public class BaiduAddressUtil {

/**
* 百度地图申请的ak
*/
@Value("${baidu.map.ak}")
private String AK;

public String getAddress(String ip) {
String address = "";
try {
// 这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
JSONObject resultJson = readJsonFromUrl("http://api.map.baidu.com/location/ip?ip=" + ip + "&ak=" + AK);
//resultJson 是返回结果,当前只取位置信息
address = ((JSONObject) resultJson.get("content")).getString("address");
} catch (Exception e) {
e.printStackTrace();
}
return address;
}

/**
* 读取
*
* @param rd
* @return
* @throws IOException
*/
private static String readAll(BufferedReader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}

/**
* 创建链接
*
* @param url
* @return
* @throws IOException
* @throws JSONException
*/
private static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = JSONObject.parseObject(jsonText);
return json;
} finally {
is.close();
}
}
}

结果示例:

Springboot 整合百度地图 API_spring_04

好,就到这。

举报

相关推荐

0 条评论