百度地图api服务端根据经纬度得到地址

2018/09/01 20:09
阅读数 24

 

package com.haiyisoft.cAssistant.mapApi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class GetAddressByBaidu {
public static Map<String, Object> getCity(String lngs,String lats) throws IOException {
String lng = null;
String lat = null;
Map<String, Object> map = new HashMap<String, Object>();
try {
lat = java.net.URLEncoder.encode(lats, "UTF-8");
lng = java.net.URLEncoder.encode(lngs, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String lngAndlat = lat+","+lng;
String key = "你的key";
String url = String.format("http://api.map.baidu.com/geocoder/v2/?ak=%s&location=%s&output=json&pois=1", key ,lngAndlat);
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;
String country = "";
String province = "";
String city = "";
String district = "";
String street = "";
String street_number = "";
while((data= br.readLine())!=null){
JSONObject para = JSONObject.parseObject(data);
if(para!=null){
String result = para.getString("result");
JSONObject paras = JSONObject.parseObject(result);
if(paras!=null){
String addressComponent = paras.getString("addressComponent");
JSONObject parasl = JSONObject.parseObject(addressComponent);
//System.out.println(parasl.toString());
if(parasl!=null){
country = parasl.getString("country");
province = parasl.getString("province");
city = parasl.getString("city");
district = parasl.getString("district");
street = parasl.getString("street");
street_number = parasl.getString("street_number");
}
}
}
}
map.put("country", country);
map.put("province", province);
map.put("city", city);
map.put("district", district);
map.put("street", street);
map.put("street_number", street_number);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(insr!=null){
insr.close();
}
if(br!=null){
br.close();
}
}
return map;
}
public static void main(String[] args) throws IOException {
Map<String, Object> detail = getCity("121.378452","37.527401");
System.out.println(detail.get("country")+","+detail.get("province")+detail.get("district")+detail.get("street")+detail.get("street_number"));
}
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部