Java实现百度地图距离计算

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!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值