/**
* 根据百度地图经纬度获取位置信息
**/
public class BaiduMapUtils {
// 百度地图秘钥
static String ak = "此处添加你的百度地图秘钥";
/**
* 根据经纬度获取位置信息 getLocationInfo
*
* @param longitude: 经度
* @param latitude: 纬度
**/
public static Map<String, Object> getLocationInfo(String longitude, String latitude) {
String urlString = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&location=" + latitude + "," + longitude;
StringBuilder res = new StringBuilder();
BufferedReader in = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
res.append(line).append("\n");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return JSON.parseObject(res.toString(), Map.class);
}
//测试
public static void main(String[] args) {
Map<String, Object> map = getLocationInfo("116.472673", "40.108383");
if (!ObjectUtils.isEmpty(map) && "0".equals(String.valueOf(map.get("status")))) {
Map result = JSONObject.parseObject(String.valueOf(map.get("result")), Map.class);
String formattedAddress = result.get("formatted_address").toString();
String business = result.get("business").toString();
System.out.println("地址:" + formattedAddress + "," + business);
}
}
}
结果: