1 package com.baidumap;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.net.URLConnection;
9
10 import org.springframework.util.StringUtils;
11
12 import com.sankai.zhcloud.util.entity.LatitudeAndLongitude;
13
14 import net.sf.json.JSONObject;
15
16 public class LngAndLatUtil {
17
18 /**
19 * 根据地址获得经纬度
20 */
21 public static LatitudeAndLongitude getLngAndLat(String address) {
22 LatitudeAndLongitude latAndLng = new LatitudeAndLongitude();
23 String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=自己注册的ak值";
24 String json = loadJSON(url);
25 if (StringUtils.isEmpty(json)) {
26 return latAndLng;
27 }
28 int len = json.length();
29 // 如果不是合法的json格式
30 if (json.indexOf("{") != 0 || json.lastIndexOf("}") != len - 1) {
31 return latAndLng;
32 }
33 JSONObject obj = JSONObject.fromObject(json);
34 if (obj.get("status").toString().equals("0")) {
35 double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
36 double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
37 latAndLng.setLatitude(lat);
38 latAndLng.setLongitude(lng);
39 }
40 return latAndLng;
41 }
42
43 public static String loadJSON(String url) {
44 StringBuilder json = new StringBuilder();
45 try {
46 URL urlObj = new URL(url);
47 URLConnection uc = urlObj.openConnection();
48 BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
49 String inputLine = null;
50 while ((inputLine = br.readLine()) != null) {
51 json.append(inputLine);
52 }
53 br.close();
54 } catch (MalformedURLException e) {
55 } catch (IOException e) {
56 }
57 return json.toString();
58 }
59
60 /**
61 * 测试方法 说明:把代码中的ak值(红色字部分)更改为你自己的ak值,在百度地图API中注册一下就有。
62 * 百度路径:http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
63 */
64 public static void main(String[] args) {
65 LatitudeAndLongitude latAndLng = LngAndLatUtil.getLngAndLat("天安门");
66 System.out.println("经度:" + latAndLng.getLongitude() + "---纬度:" + latAndLng.getLatitude());
67 }
68
69
70 /**
71 * 补充:计算两点之间真实距离
72 * @return 米
73 */
74 public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
75 // 维度
76 double lat1 = (Math.PI / 180) * latitude1;
77 double lat2 = (Math.PI / 180) * latitude2;
78
79 // 经度
80 double lon1 = (Math.PI / 180) * longitude1;
81 double lon2 = (Math.PI / 180) * longitude2;
82
83 // 地球半径
84 double R = 6371;
85
86 // 两点间距离 km,如果想要米的话,结果*1000就可以了
87 double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
88
89 return d * 1000;
90 }
91
92 }