java实现根据高德地图API接口进行地址位置解析,将地址转化为经纬度
原创文章,转载请注明,欢迎评论和更改。
1,所需额外ar包,import net.sf.json.JSONObject;
2,完整源代码代码
复制代码
package com.travel.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONObject;
public class AddressLngLatExchange {
public String getLngLat(String address) {
StringBuffer json = new StringBuffer();
try {
URL u = new URL("http://restapi.amap.com/v3/geocode/geo?address="+address+"&output=JSON&key=7f4ffae4074e8b8e4d147190527a4b72");
URLConnection yc = u.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 (Exception e) {
e.printStackTrace();
}
String jsonStr=json.toString();
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
//判断输入的位置点是否存在
if(jsonObject.getJSONArray("geocodes").size()>0)
return jsonObject.getJSONArray("geocodes").getJSONObject(0).get("location").toString();
else
return null;
}
public static void main(String[] args) {
AddressLngLatExchange addressLngLatExchange=new AddressLngLatExchange();
System.out.println(addressLngLatExchange.getLngLat("北京"));
}
}
高德地图的key在高德开放平台的控制台中添加, 坐标转换属于web服务
//百度地图也记录一下
public Object[] getCoordinate(String addr) throws IOException {
String lon = null;//经度
String lat = null;//纬度
String address = null;
try {
address = java.net.URLEncoder.encode(addr, "UTF-8");
}catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String key = "f247cdb592eb43ebac6ccd27f796e2d2";
String url = String .format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStreamReader insr = null;
BufferedReader br = null;
try {
httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
if (httpsConn != null) {
insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
br = new BufferedReader(insr);
String data = null;
int count = 1;
while((data= br.readLine())!=null){
if(count==5){
lon = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
count++;
}else if(count==6){
lat = data.substring(data.indexOf(":")+1);//纬度
count++;
}else{
count++;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(insr!=null){
insr.close();
}
if(br!=null){
br.close();
}
}
return new Object[]{lat,lon};
}