1.注册自己百度应用取得AK码
**2.需要的Jar包 **
类型服务端
白名单不想限制就写 0.0.0.0/0
取得自己的AK码
jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<base href="<%=basePath%>" >
</head>
<body>
<form action="map/showMap" method="post">
起点:<input type="text" name="origins"/>
终点:<input type="text" name="destinations"/>
<input type="submit" value="提交"/>
</form>
<table>
<tr>
<td>时间</td>
<td>总里程数</td>
<td>总公里数</td>
</tr>
<c:forEach var="page" items="${mapList}">
<tr>
<td>${page.mTime}</td>
<td>${page.mZlc}</td>
<td>${page.mZzlc}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
控制层
package cn.hr.controller;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.hr.util.HttpClientUtil;
@Controller
@RequestMapping("/map")
public class MapController {
@RequestMapping(value = "showMap",method = RequestMethod.POST)
public String showMap(@RequestParam("origins") String origins,
@RequestParam("destinations")String destinations,
HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>();
String originDouble = HttpClientUtil
.doGet("http://api.map.baidu.com/geocoder/v2/?output=json&ak=自己的ak&address="
+origins );
String desDouble = HttpClientUtil
.doGet("http://api.map.baidu.com/geocoder/v2/?output=json&ak=自己的AK&address="
+ destinations);
JSONObject jsonObjectOri = JSONObject.parseObject(originDouble);
JSONObject jsonObjectDes = JSONObject.parseObject(desDouble);
String oriLng = jsonObjectOri.getJSONObject("result").getJSONObject("location").getString("lng");// 经度值ֵ
String oriLat = jsonObjectOri.getJSONObject("result").getJSONObject("location").getString("lat");// 纬度值ֵ
String desLng = jsonObjectDes.getJSONObject("result").getJSONObject("location").getString("lng");
String desLat = jsonObjectDes.getJSONObject("result").getJSONObject("location").getString("lat");
params.put("output", "json");//输出方式为json
params.put("tactics", "11");//10不走高速11常规路线12 距离较短(考虑路况)13距离较短(不考虑路况)
params.put("ak", "自己的ak");
// origins 起点 destinations 目的地
params.put("origins", oriLat + "," + oriLng + "|" + oriLat + "," + oriLng);
params.put("destinations", desLat + "," + desLng + "|" + desLat + "," + desLng);
String result = HttpClientUtil.doGet("http://api.map.baidu.com/routematrix/v2/driving", params);
JSONArray jsonArray = JSONObject.parseObject(result).getJSONArray("result");
//获取json长度
int JsonLen = 0;
for (Object object : jsonArray) {
//System.out.println(object);
JsonLen++;
}
//System.out.println("推荐方案:");
List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
Map<String,String> map = null;
int i;
for (i = 0; i < JsonLen; i++) {
map = new HashMap<String,String>();
map.put("mTime",jsonArray.getJSONObject(i).getJSONObject("duration").getString("text"));
map.put("mZlc",jsonArray.getJSONObject(i).getJSONObject("distance").getString("text"));
map.put("mZzlc",jsonArray.getJSONObject(i).getJSONObject("distance").getString("value"));
}
mapList.add(map);
request.setAttribute("mapList", mapList);
return "map";
}
}
工具类
package cn.hr.util;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
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;
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(),
"UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
// if (param != null) {
// List<NameValuePair> paramList = new ArrayList<>();
// for (String key : param.keySet()) {
// paramList.add(new BasicNameValuePair(key, param.get(key)));
// }
// UrlEncodedFormEntity entity = new
// UrlEncodedFormEntity(paramList);
// httpPost.setEntity(entity);
// }
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json,
ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
}
测试
知识点
其实就是通过自己的AK,起点,终点,到百度API查询返回JSON取值输入而已
Over!!!