public static String getLnglat(String address, String AMAPkey) {
//"http://restapi.amap.com/v3/geocode/geo?address=上海市东方明珠&output=JSON&key=xxxxxxxxx";
String geturl = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + AMAPkey;
String location = "";
try {
URL url = new URL(geturl); // 把字符串转换为URL请求地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
connection.connect();// 连接会话
// 获取输入流
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {// 循环读取流
sb.append(line);
}
br.close();// 关闭流
connection.disconnect();// 断开连接
JSONObject a = JSON.parseObject(sb.toString());
//判断输入的位置点是否存在
System.out.println(sb.toString());
if (a.getJSONObject("result").size() > 0) {
String lng = String.valueOf(a.getJSONObject("result").getJSONObject("location").get("lng"));
String lat = String.valueOf(a.getJSONObject("result").getJSONObject("location").get("lat"));
location = lng + "," + lat;
}
System.out.println(location);
} catch (Exception e) {
e.printStackTrace();
System.out.println("失败!");
}
return location;
}
文章评论