Java调用百度Api获取当前位置信息
在项目中可以调用API接口利用IP获取大致位置,返回请求参数中指定上网IP的大致位置信息(一般为城市级别),位置信息包括:经纬度、省、市等地址信息。
1.在百度api官网注册一个账号,并创建一个应用
2.注册好之后拿到密钥AK,根据百度Api开发文档中请求参数的要求进行配置
3.开始用Java编写代码实现定位信息(注:如果是本地环境调用,ip设置为空或者不写,生产环境使用生产环境的IP地址)
/**
* @description java实现百度地图定位
* @author shmily
*/
public class BaiduMapUtil {
public static void main(String[] args) {
System.out.println(getAddress(""));
}
public static String getAddress(String ip) {
String address = "";
String ak = "你的AK";
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+"&coor=bd09ll");
//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();
}
}
}
运行结果