Java实现百度地图距离计算

1.注册自己百度应用取得AK码
**2.需要的Jar包 **
在这里插入图片描述
Java实现百度地图距离计算_第1张图片
类型服务端
白名单不想限制就写 0.0.0.0/0
Java实现百度地图距离计算_第2张图片
取得自己的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"%>



<% 
	String path = request.getContextPath(); 
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

Insert title here



	
起点: 终点:
时间 总里程数 总公里数
${page.mTime} ${page.mZlc} ${page.mZzlc}

控制层

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 params = new HashMap();
		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> mapList = new ArrayList>();
		Map map = null;
		int i;
		for (i = 0; i < JsonLen; i++) {
			map = new HashMap();
			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 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 param) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			// if (param != null) {
			// List 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;
	}
}

测试
Java实现百度地图距离计算_第3张图片
Java实现百度地图距离计算_第4张图片
知识点
其实就是通过自己的AK,起点,终点,到百度API查询返回JSON取值输入而已
Over!!!

你可能感兴趣的:(百度地图)