注意:java后端调百度地图,走HTTP请求,HTTP请求一般较慢。
百度官方API地址
http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi
单个地址查询返回信息用Map封装
转换JSON实体类
public class SingleAddressBean {
private String area;
private String uid;
private String address;
private String province;
private String city;
private String adcode;
private String name;
private String location;
private String detail;
public SingleAddressBean(){
}
public SingleAddressBean(String area, String uid, String address, String province, String city, String adcode, String name, String location, String detail) {
this.area = area;
this.uid = uid;
this.address = address;
this.province = province;
this.city = city;
this.adcode = adcode;
this.name = name;
this.location = location;
this.detail = detail;
}
@Override
public String toString() {
return "ResultBean{" +
"area='" + area + '\'' +
", uid='" + uid + '\'' +
", address='" + address + '\'' +
", province='" + province + '\'' +
", city='" + city + '\'' +
", adcode='" + adcode + '\'' +
", name='" + name + '\'' +
", location='" + location + '\'' +
", detail='" + detail + '\'' +
'}';
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAdcode() {
return adcode;
}
public void setAdcode(String adcode) {
this.adcode = adcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
请求方法代码
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class SearchAddressDemo {
static String MYAK = ""; // 百度地图密钥
public static void main(String[] args) {
String dom = "安徽省蚌埠市固镇县";
Map map = getCoordinate(dom);
System.out.println("map: "+map);
}
//单个地址查询
public static Map getCoordinate(String address) {
Map<String,String> map = new HashMap<>();
if (address != null && !"".equals(address)) {
String url = "http://api.map.baidu.com/place/v2/search?query="+address+"®ion=全国&extensions_adcode=true&output=json&ak="+MYAK;
String json = loadJSON(url);
if (json != null && !"".equals(json)) {
JSONObject obj = JSONObject.parseObject(json);
JSONArray array = obj.getJSONArray("results"); //如果json格式的字符串里含有数组格式的属性,将其转换成JSONArray,以方便后面转换成对应的实体
if ("0".equals(obj.getString("status"))) {
JSONObject jsonObject =(JSONObject ) array.get(0); //将array中的数据进行逐条转换
SingleAddressBean singleAddressBean =JSONObject.toJavaObject(jsonObject, SingleAddressBean.class); //通过JSONObject.toBean()方法进行对象间的转换
String area = singleAddressBean.getArea();
String uid = singleAddressBean.getUid();
String province = singleAddressBean.getProvince();
String city = singleAddressBean.getCity();
String adcode = singleAddressBean.getAdcode();
String name = singleAddressBean.getName();
String location = singleAddressBean.getLocation();
if(location==null||location.isEmpty()||"".equals(location)){
return map;
}
String lng = cutString(location,"lng",",");
String lat = cutString(location,"lat","}");
String detail = singleAddressBean.getDetail();
location = lat+","+lng;
map.put("area",area);
map.put("uid",uid);
map.put("province",province);
map.put("city",city);
map.put("adcode",adcode);
map.put("name",name);
map.put("location",location);
map.put("detail",detail);
}
}
return map;
}
return null;
}
public static String cutString(String allStr,String startLog,String endLog){
allStr = allStr.substring(allStr.indexOf(startLog),allStr.indexOf(endLog));
allStr = allStr.substring(startLog.length()+2,allStr.length());
return allStr;
}
public static String loadJSON(String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.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 (MalformedURLException e) {} catch (IOException e) {}
return json.toString();
}
}
多个地址查询返回值封装成Map(因为通过地址检索反馈的信息太少,不符合需求,所以又通过坐标第二次批量检索。)
转换JSON实体类
public class MultiCoordBean {
private String level;
private String confidence;
private String location;
private String precise;
private String comprehension;
private String status;
public MultiCoordBean(){}
public MultiCoordBean(String level, String confidence, String location, String precise, String comprehension, String status) {
this.level = level;
this.confidence = confidence;
this.location = location;
this.precise = precise;
this.comprehension = comprehension;
this.status = status;
}
@Override
public String toString() {
return "ManyResultBean{" +
"level='" + level + '\'' +
", confidence='" + confidence + '\'' +
", location='" + location + '\'' +
", precise='" + precise + '\'' +
", comprehension='" + comprehension + '\'' +
", status='" + status + '\'' +
'}';
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getConfidence() {
return confidence;
}
public void setConfidence(String confidence) {
this.confidence = confidence;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPrecise() {
return precise;
}
public void setPrecise(String precise) {
this.precise = precise;
}
public String getComprehension() {
return comprehension;
}
public void setComprehension(String comprehension) {
this.comprehension = comprehension;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
public class MultiAddressBean {
private String country;
private String country_code;
private String country_code_iso;
private String country_code_iso2;
private String province;
private String city;
private String city_level;
private String district;
private String town;
private String town_code;
private String adcode;
private String street;
private String street_number;
private String direction;
private String distance;
public MultiAddressBean(){}
public MultiAddressBean(String country, String country_code, String country_code_iso, String country_code_iso2, String province, String city, String city_level, String district, String town, String town_code, String adcode, String street, String street_number, String direction, String distance) {
this.country = country;
this.country_code = country_code;
this.country_code_iso = country_code_iso;
this.country_code_iso2 = country_code_iso2;
this.province = province;
this.city = city;
this.city_level = city_level;
this.district = district;
this.town = town;
this.town_code = town_code;
this.adcode = adcode;
this.street = street;
this.street_number = street_number;
this.direction = direction;
this.distance = distance;
}
@Override
public String toString() {
return "MultiAddressBean{" +
"country='" + country + '\'' +
", country_code='" + country_code + '\'' +
", country_code_iso='" + country_code_iso + '\'' +
", country_code_iso2='" + country_code_iso2 + '\'' +
", province='" + province + '\'' +
", city='" + city + '\'' +
", city_level='" + city_level + '\'' +
", district='" + district + '\'' +
", town='" + town + '\'' +
", town_code='" + town_code + '\'' +
", adcode='" + adcode + '\'' +
", street='" + street + '\'' +
", street_number='" + street_number + '\'' +
", direction='" + direction + '\'' +
", distance='" + distance + '\'' +
'}';
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry_code() {
return country_code;
}
public void setCountry_code(String country_code) {
this.country_code = country_code;
}
public String getCountry_code_iso() {
return country_code_iso;
}
public void setCountry_code_iso(String country_code_iso) {
this.country_code_iso = country_code_iso;
}
public String getCountry_code_iso2() {
return country_code_iso2;
}
public void setCountry_code_iso2(String country_code_iso2) {
this.country_code_iso2 = country_code_iso2;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCity_level() {
return city_level;
}
public void setCity_level(String city_level) {
this.city_level = city_level;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getTown_code() {
return town_code;
}
public void setTown_code(String town_code) {
this.town_code = town_code;
}
public String getAdcode() {
return adcode;
}
public void setAdcode(String adcode) {
this.adcode = adcode;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getStreet_number() {
return street_number;
}
public void setStreet_number(String street_number) {
this.street_number = street_number;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
请求方法代码
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SearchManyAddressDemo {
static String MYAK = "";
static String URL = "http://api.map.baidu.com/batch";
public static void main(String[] args) throws Exception{
String address01 = "安徽省合肥市三孝口";
String address02 = "安徽省蚌埠市固镇县";
String address03 = "6666";
List<String> list = new ArrayList<>();
list.add(address01);
list.add(address02);
list.add(address03);
List<Map> result = MultilGetAddress(list);
System.out.println(""); System.out.println("");
for(Map map :result){
System.out.println(map);
}
}
//多地址查询返回 Map
public static List<Map> MultilGetAddress(List<String> list) {
//最多一次查20个地址
if(list==null||list.isEmpty()||list.size()>20){
return null;
}
String myAk = "";
String url = "http://api.map.baidu.com/batch";
String json = "{\"reqs\":[" ;
StringBuilder builder = new StringBuilder();
builder.append(json);
for(int i=0;i<list.size()-1;i++){
String address = list.get(i);
String newJson = "{\"method\":\"get\",\"url\":\"/geocoding/v3/?output=json&ak="+myAk+"&address="+address+"\"},";
builder.append(newJson);
}
int size = list.size()-1;
String address = list.get(size);
String endJson = "{\"method\":\"get\",\"url\":\"/geocoding/v3/?output=json&ak="+myAk+"&address="+address+"\"}]}";
builder.append(endJson);
String data = builder.toString();
String coordResponse = sendPost(url,data);
List<String> locaList = new ArrayList<>();
JSONObject obj = JSONObject.parseObject(coordResponse);
if (coordResponse != null && !"".equals(coordResponse)&&"0".equals(obj.getString("status"))) {
JSONArray array = obj.getJSONArray("batch_result");
int arrSize = array.size();
System.out.println(" size "+ array.size());
for(int i=0;i<arrSize;i++){
JSONObject jsonObject =(JSONObject ) array.get(i);
String status = jsonObject.getString("status");
if("0".equals(status)){
JSONObject jt =jsonObject.getJSONObject("result");
MultiCoordBean MultiCoordBean =JSONObject.toJavaObject(jt, MultiCoordBean.class);
String location = MultiCoordBean.getLocation();
String lng = cutString(location,"lng",",");
String lat = cutString(location,"lat","}");
location = lat+","+lng;
locaList.add(location);
}else {
MultiCoordBean MultiCoordBean = new MultiCoordBean();
MultiCoordBean.setStatus("1");
locaList.add("null");
}
}
}else {
return null;
}
List<Map> multiAddressList = new ArrayList<>();
String json02 = "{\"reqs\":[" ;
StringBuilder builder02 = new StringBuilder();
builder02.append(json02);
for(int i=0;i<locaList.size()-1;i++){
String local = locaList.get(i);
String newJson ="{\"method\":\"get\",\"url\":\"/reverse_geocoding/v3/?location="+local+"&output=json&entensions_poi=0&ak="+myAk+"\"},";
builder02.append(newJson);
}
int size02 = locaList.size()-1;
String local = locaList.get(size02);
String endJson02 = "{\"method\":\"get\",\"url\":\"/reverse_geocoding/v3/?location="+local+"&output=json&entensions_poi=0&ak="+myAk+"\"}]}";
builder02.append(endJson02);
String data02 = builder02.toString();
String addressResults = sendPost(url,data02);
JSONObject addressJSONObj = JSONObject.parseObject(addressResults);
if (addressResults != null && !"".equals(addressResults)&&"0".equals(addressJSONObj.getString("status"))) {
JSONArray addressArray = addressJSONObj.getJSONArray("batch_result");
int arrSize = addressArray.size();
for(int i=0;i<arrSize;i++){
JSONObject jsonObject =(JSONObject ) addressArray.get(i);
String status = jsonObject.getString("status");
if("0".equals(status)){
JSONObject resultObj =jsonObject.getJSONObject("result");
String location = resultObj.getString("location");
String lng = cutString(location,"lng",",");
String lat = cutString(location,"lat","}");
location = lat+","+lng;
JSONObject addressComponentObj =resultObj.getJSONObject("addressComponent");
MultiAddressBean multiAddressBean =JSONObject.toJavaObject(addressComponentObj,MultiAddressBean.class);
String adcode = multiAddressBean.getAdcode();
String city = multiAddressBean.getCity();
String province = multiAddressBean.getProvince();
Map<String,String> map = new HashMap<>();
map.put("location",location);
map.put("adcode",adcode);
map.put("city",city);
map.put("province",province);
multiAddressList.add(map);
}else {
Map<String,String> map = new HashMap<>();
multiAddressList.add(map);
}
}
}else {
return null;
}
return multiAddressList;
}
public static String sendPost(String url,String data) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity stringentity = new StringEntity(data,
ContentType.create("text/json", "UTF-8"));
httppost.setEntity(stringentity);
httpresponse = httpclient.execute(httppost);
response = EntityUtils.toString(httpresponse.getEntity());
} finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
public static String cutString(String allStr,String startLog,String endLog){
allStr = allStr.substring(allStr.indexOf(startLog),allStr.indexOf(endLog));
allStr = allStr.substring(startLog.length()+2,allStr.length());
return allStr;
}
}