public class BaiduApiUtil {
/**
* @author wangqiang
* @ClassName BaiduAPI.java
* @Description 百度API接口-地址转经纬度
* @createTime 2022-03-08 14:40
* @addr 地址
**/
public static Map<String, Double> getLatAndLngByAddress(String addr) {
String address = "";
String lat = "";
String lng = "";
try {
address = java.net.URLEncoder.encode(addr, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String url = "https://api.map.baidu.com/geocoding/v3/?address=" + address +
"&output=json&ak=桶名称&callback=showLocation ";
URL myURL = null;
URLConnection httpsConn = null;
//进行转码
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
}
try {
httpsConn = (URLConnection) myURL.openConnection();
if (httpsConn != null) {
InputStreamReader insr = new InputStreamReader(
httpsConn.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(insr);
String data = null;
if ((data = br.readLine()) != null) {
lat = data.substring(data.indexOf("\"lat\":")
+ ("\"lat\":").length(), data.indexOf("},\"precise\""));
lng = data.substring(data.indexOf("\"lng\":")
+ ("\"lng\":").length(), data.indexOf(",\"lat\""));
}
insr.close();
}
} catch (IOException e) {
}
Map<String, Double> map = new HashMap<String, Double>();
map.put("lat", new Double(lat));
map.put("lng", new Double(lng));
return map;
}
}