package org.hanghao.utils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import net.sf.json.JSONObject;
/***
* 百度地图API接口 工具类
*
* @author Long Tanglin
* @since 2017-5-9 13:59:46
*/
public class BaiduUtil {
public static Properties prop = null;
static {
prop = new Properties();
try {
String property = System.getProperty("user.dir");
String path = property + File.separator + "config" + File.separator + "baidu.properties"; //ak=自己的应用ak
InputStream in = new BufferedInputStream(new FileInputStream(path));
prop.load(in); // 加载属性列表
in.close();
} catch (Exception e) {
System.out.println(e);
}
}
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()));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return json.toString();
}
/***
* 获取地址的经纬度
*
* @param address
* 地址
* @return json 经纬度
*/
public static JSONObject getLngLat(String address) {
JSONObject jsonObject = new JSONObject();
if (address != null)
address = address.trim();
String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak="
+ prop.getProperty("ak");
String json = loadJSON(url);
JSONObject obj = JSONObject.fromObject(json);
if (obj.get("status").toString().equals("0")) {
double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
jsonObject.put("status", 1);
jsonObject.put("lng", lng);
jsonObject.put("lat", lat);
} else {
jsonObject.put("status", 0);
jsonObject.put("msg", "未找到匹配的经纬度,请输入详细的地址。");
}
return jsonObject;
}
/***
* 获取地理位置
*
* @param lat
* 纬度
* @param lng
* 经度
* @return JSON 地理位置
* @throws IOException
*/
public static JSONObject getLocation(String lat, String lng) throws IOException {
String location = lat+","+lng;
URL url = new URL("http://api.map.baidu.com/geocoder?ak=" + prop.getProperty("ak")
+ "&callback=renderReverse&location="+location+"&output=json");
URLConnection connection = url.openConnection();
/*
* 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
*/
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
out.flush();
out.close();
// 一旦发送成功,用以下方法就可以得到服务器的回应:
String res;
InputStream l_urlStream;
l_urlStream = connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
StringBuilder sb = new StringBuilder("");
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
String str = sb.toString();
JSONObject jsonObject = new JSONObject();
if (StringUtils.isNotEmpty(str)) {
int addStart = str.indexOf("formatted_address\":");
int addEnd = str.indexOf("\",\"business");
if (addStart > 0 && addEnd > 0) {
String address = str.substring(addStart + 20, addEnd);
jsonObject.put("address", address);
return jsonObject;
}
}
return jsonObject;
}
/***
* 获取两个地理坐标的直线距离
*
* @param Lat_A
* A点纬度
* @param Lng_A
* A点经度
* @param Lat_B
* B点纬度
* @param Lng_B
* B点经度
* @return 距离 单位为"千米" 3位小数 ###.000
*/
public static double getDistance(double Lat_A, double Lng_A, double Lat_B, double Lng_B) {
double ra = 6378.140;
double rb = 6356.755;
double flatten = (ra - rb) / ra;
double rad_lat_A = Math.toRadians(Lat_A);
double rad_lng_A = Math.toRadians(Lng_A);
double rad_lat_B = Math.toRadians(Lat_B);
double rad_lng_B = Math.toRadians(Lng_B);
double pA = Math.atan(rb / ra * Math.tan(rad_lat_A));
double pB = Math.atan(rb / ra * Math.tan(rad_lat_B));
double xx = Math
.acos(Math.sin(pA) * Math.sin(pB) + Math.cos(pA) * Math.cos(pB) * Math.cos(rad_lng_A - rad_lng_B));
double c1 = (Math.sin((xx) - xx) * (Math.sin(pA) + Math.sin(pB)) * 2 / Math.cos(xx / 2) * 2);
double c2 = (Math.sin(xx) + xx) * (Math.sin(pA) - Math.sin(pB)) * 2 / Math.sin(xx / 2) * 2;
double dr = flatten / 8 * (c1 - c2);
double distance = ra * (xx + dr);
DecimalFormat format = new DecimalFormat("###.000");
distance = Double.parseDouble(format.format(distance));
return distance;
}
}
package com.henghao.controller;
import java.io.IOException;
import org.hanghao.utils.BaiduUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import net.sf.json.JSONObject;
/**
* 百度地图API 获取地址经纬度
*
* @author Long Tanglin
* @since 2017-5-9 15:57:30
*/
@Controller
@RequestMapping("/baiduMap")
public class BaiduAPIContraller {
/**
* 根据地址获取经纬度
*
* @param address
* 地址
* @return 地址经纬度
* @throws Exception
*/
@RequestMapping("/getLngLat")
@ResponseBody
public JSONObject getLngLat(@RequestParam(required = false) String company,
@RequestParam(required = false) String address) throws Exception {
if (company != null) {
company = company.trim();
company = new String(company.getBytes("iso-8859-1"), "utf-8");
}
if (address != null) {
address = address.trim();
address = new String(address.getBytes("iso-8859-1"), "utf-8");
}
String addressName = company + address;
JSONObject lnglat = BaiduUtil.getLngLat(addressName);
return lnglat;
}
/***
* 根据坐标位置获取地理位置
*
* @param lat
* 纬度
* @param lng
* 经度
* @return 地理位置
* @throws IOException
*/
@RequestMapping("/getLocation")
public JSONObject getLocation(@RequestParam(required = true) String lat, @RequestParam(required = true) String lng)
throws IOException {
lat = lat.trim();
lng = lng.trim();
JSONObject location = BaiduUtil.getLocation(lat, lng);
return location;
}
/***
* 获取两个地理坐标的直线距离
*
* @param Lat_A
* A点纬度
* @param Lng_A
* A点经度
* @param Lat_B
* B点纬度
* @param Lng_B
* B点经度
* @return 距离 单位为"千米" 3位小数 ###.000
* @throws Exception
*/
@RequestMapping("/getDistance")
public double getDistance(@RequestParam(required = true) String Lat_A, @RequestParam(required = true) String Lng_A,
@RequestParam(required = true) String Lat_B, @RequestParam(required = true) String Lng_B) throws Exception {
double latA = Double.parseDouble(Lat_A);
double lngA = Double.parseDouble(Lng_B);
double latB = Double.parseDouble(Lat_A);
double lngB = Double.parseDouble(Lng_B);
double distance = BaiduUtil.getDistance(latA, lngA, latB, lngB);
return distance;
}
/***
* 获取两地最短行程距离 交通方式为驾车
* @param Lat_A 起点纬度
* @param Lng_A 起点经度
* @param Lat_B 终点纬度
* @param Lng_B 终点经度
* @return 两地的距离和最短耗时 数据 JSON格式
*/
public static JSONObject getMinimumTravel(String Lat_A, String Lng_A, String Lat_B, String Lng_B){
JSONObject jsonObject = new JSONObject();
String lnglats = Lat_A+","+Lng_A;
String lnglate = Lat_B+","+Lng_B;
String url = "http://api.map.baidu.com/routematrix/v2/driving?tactics=12&origins="+lnglats+
"&destinations="+lnglate+"&output=json&ak="+prop.get("ak");
String loadJSON = loadJSON(url);
JSONObject jsonData = JSONObject.fromObject(loadJSON);//格式化为JSON
JSONObject json = (JSONObject) ((JSONArray)jsonData.get("result")).get(0);
JSONObject distance = (JSONObject)json.get("distance");
JSONObject duration = (JSONObject)json.get("duration");
jsonObject.put("distance", distance.get("value"));
jsonObject.put("duration", duration.get("text"));
return jsonObject;
}
}