/**
* 通过地址获取经纬度
* @param addr
* @return
*/
public static Map<String, BigDecimal> getLatAndLngByAddress(String addr) {
String address = "";
try {
address = java.net.URLEncoder.encode(addr,"UTF-8");
} catch (Exception e1) {
e1.printStackTrace();
}
//http://api.map.baidu.com/place/v2/search?ak=你的ak&output=json&query=%s®ion=全国
String url = String.format("http://api.map.baidu.com/place/v2/search?ak=你的ak&output=json&query=%s®ion=全国",address);
URL myURL = null;
URLConnection httpsConn = null;
//进行转码
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
}
StringBuffer sb = new StringBuffer();
try {
httpsConn = (URLConnection) myURL.openConnection();
if (httpsConn != null) {
InputStreamReader insr = new InputStreamReader(
httpsConn.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(insr);
String data = null;
while ((data = br.readLine()) != null) {
sb.append(data);
}
insr.close();
}
} catch (IOException e) {
}
Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
JSONObject resultJson = JSONObject.fromObject(sb.toString());
JSONArray jsonArray = (JSONArray)resultJson.get("results");
JSONObject results0Obj = (JSONObject)jsonArray.get(0);
JSONObject locationObj = (JSONObject)results0Obj.get("location");
//纬度
System.out.println(locationObj.get("lat"));
//经度
System.out.println(locationObj.get("lng"));
return map;
}
需要的pom依赖
<!-- 计算经纬度距离 -->
<!-- https://mvnrepository.com/artifact/org.gavaghan/geodesy -->
<dependency>
<groupId>org.gavaghan</groupId>
<artifactId>geodesy</artifactId>
<version>1.1.3</version>
</dependency>