/**
* 高德地图通过地址获取经纬度
*/
public static String GaodeLocation(String address) {
String geturl = "http://restapi.amap.com/v3/geocode/geo?key=xxxxxxxx&address="+address;
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());
JSONArray sddressArr = JSON.parseArray(a.get("geocodes").toString());
JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
location = c.get("location").toString();
System.out.println(location);
} catch (Exception e) {
e.printStackTrace();
System.out.println("失败!");
}
return location;
}
该接口返回数据格式如下,以上代码提取了最终需要的经纬度location。
{
"status": "1",
"info": "OK",
"infocode": "10000",
"count": "1",
"geocodes": [
{
"formatted_address": "浙江省杭州市滨江区",
"country": "中国",
"province": "浙江省",
"citycode": "0571",
"city": "杭州市",
"district": "滨江区",
"township": [],
"neighborhood": {
"name": [],
"type": []
},
"building": {
"name": [],
"type": []
},
"adcode": "330108",
"street": [],
"number": [],
"location": "120.146505,30.162450",
"level": "区县"
}
]
}
// 需要在腾讯地图申请一个KEY
private static final String KEY ="";
/**
* 腾讯地图根据地址获取经纬度
* @param address 地址
* @return
*/
public static String addressToLocation(String address) {
String urlString ="https://apis.map.qq.com/ws/geocoder/v1/?address=" + address + "&key=" + KEY ;
//请求的url
URL url = null;
//请求的输入流
BufferedReader in = null;
//输入流的缓冲
StringBuffer sb = new StringBuffer();
try{
url = new URL(urlString);
in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") );
String str = null;
while((str = in.readLine()) != null) {
sb.append( str );
}
} catch (Exception ex) {
} finally{
try{
if(in!=null) {
in.close(); //关闭流
}
}catch(IOException ex) {
}
}
JSONObject message = JSONObject.parseObject(sb.toString());
JSONObject result = JSONObject.parseObject(message.get("result").toString());
JSONObject location = JSONObject.parseObject(result.get("location").toString());
String lng = location.get("lng").toString();
String lat = location.get("lat").toString();
String coordinate = lng+","+lat;
return coordinate;
}
由于腾讯地图的返回数据格式如下,而业务需要经纬度,因此提取详细经纬度location并拼接成为需要的字符串。
{
"status": 0,
"message": "query ok",
"result": {
"title": "滨江区",
"location": {
"lng": 120.21201,
"lat": 30.2084
},
"ad_info": {
"adcode": "330108"
},
"address_components": {
"province": "浙江省",
"city": "杭州市",
"district": "滨江区",
"street": "",
"street_number": ""
},
"similarity": 0.8,
"deviation": 1000,
"reliability": 1,
"level": 2
}
}