根据地名获取经纬度

pom.xml   --->添加-maven 依赖包《必须要》

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>


直接上代码,可用

public String loadJSON(String url) {
    StringBuilder json = new StringBuilder();
try {
LOGGER.info("11-2");
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {} catch (IOException e) {}
return json.toString();
}


//返回值
@GetMapping("/getCoordinate")
public BaseResponse getCoordinate(String address) {
BaseResponse response = new BaseResponse();
LOGGER.info("1");
try{
LOGGER.info("2");
if (address != null && !"".equals(address)) {
LOGGER.info("3");
address = address.replaceAll("\\s*", "").replace("#", "栋");
String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=F454f8a5efe5e577997931cc01de3974";
String json = loadJSON(url);
if (json != null && !"".equals(json)) {
JSONObject obj = JSONObject.parseObject(json);
if ("0".equals(obj.getString("status"))) {
double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng"); // 经度
double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat"); // 纬度
DecimalFormat df = new DecimalFormat("#.######");
String lng1 = df.format(lng);
String lat1 = df.format(lat);
response.setData("经度:"+lng1+"纬度:"+lat1);
response.setSuccess(true);
return response;
}
}
}

}catch (Exception e){
response.setErrorMsg(ErrorCode.SYSTEM_ERROR.getDesc());
}
return response;
}


posted @ 2019-03-22 15:41  up-zyn  阅读(2411)  评论(0编辑  收藏  举报