public class GetCoordinateUtil {
public static void main(String[] args) {
try {
String[] coordinate = new GetCoordinateUtil().getCoordinate("天安门");
System.out.println(coordinate[0]+" "+coordinate[1]);
} catch (IOException e) {
e.printStackTrace();
}
Map<String, Object> map = getURLContent("天安门");
System.out.println("lng=" + map.get("lng") + ",lat=" + map.get("lat"));
}
public String[] getCoordinate(String addr) throws IOException {
String lng = null;
String lat = null;
String address = null;
try {
address = java.net.URLEncoder.encode(addr, "UTF-8");
}catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String key = "自己的KEY";
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){
lng = (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 String[]{lng,lat};
}
public static Map<String, Object> getURLContent(String address) {
String urlStr = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + address + "&key=你的KEY";
URL url = null;
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(urlStr);
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) {
}
}
String result = sb.toString();
String r = JSONObject.parseObject(result).getString("result");
String location = JSONObject.parseObject(r).getString("location");
String lng = JSONObject.parseObject(location).getString("lng");
String lat = JSONObject.parseObject(location).getString("lat");
Map<String, Object> map = new HashMap<>();
map.put("lng", lng);
map.put("lat", lat);
return map;
}
}
个人感觉 腾讯不如百度 查询精准,
拿 “天安门” 举例,百度能搜到,腾讯搜不到
另外,百度地图的经纬度和腾讯地图的经纬度 数据是反的,具体位置也有些许差别
例:查询“天津市”
百度 117.208093,39.091103
腾讯 117.30983,39.71755
需要把腾讯的反过来 39.71755,117.30983