在国内使用电子地图获取到的经纬度都不是真实的经纬度,而是经过一定的算法在真实的经纬度上添加了一个偏移量,且不同的地图有不同的算法。现在告诉大家在java中怎样对百度地图进行纠偏,主要实现将真实的经纬度在百度地图上进行显示,消除偏差。
一、若需要消偏的经纬度较少,则直接在浏览器中进行即可,百度提供了相应的API接口
1、API地址:http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=113.240324&y=23.817349
from=0:代表传入的是真实经纬度
to=4:代表返回是百度纠偏后,能在百度地图上正确显示出该地址的经纬度
x:经度 y:纬度
返回数据:{"error":0,"x":"MTEzLjI1MjIyMjUxOTg1","y":"MjMuODIwNjM5MTEyNDgy"}
返回的数据经过Base64加密,在网上找个在线Base64解密的网站就可以了
二、若数据量较大,则通过上述方式就不方便了,这里提供Java方法进行批量消偏,代码如下:
1 import java.io.IOException;
2 import org.apache.http.HttpEntity;
3 import org.apache.http.HttpResponse;
4 import org.apache.http.client.ClientProtocolException;
5 import org.apache.http.client.ResponseHandler;
6 import org.apache.http.client.methods.HttpPost;
7 import org.apache.http.impl.client.CloseableHttpClient;
8 import org.apache.http.impl.client.HttpClients;
9 import org.apache.http.util.EntityUtils;
10 import net.sf.json.JSONObject;
11
12 public class Remove {
13 public static void main(String[] args) {
14 try {
15 //这里只有一条数据,有多条数据的话可以用循环,然后拼接url字符串
16 String url = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=113.540124&y=23.517846";
17 JSONObject json = getAllEmployee(url);
18 //将经纬度解码后进行打印
19 String latitude = decode(json.getString("x"));
20 String longitude = decode(json.getString("y"));
21 System.out.println("经度为:" + latitude);
22 System.out.println("纬度为:" + longitude);
23 } catch (Exception e) {
24 e.printStackTrace();
25 }
26 }
27
28 /**
29 * Java后台访问url链接,返回JSON格式的数据
30 * @return
31 */
32 public static JSONObject getAllEmployee(String url) {
33 try {
34 CloseableHttpClient httpclient = HttpClients.createDefault();
35 HttpPost httpPost = new HttpPost(url);
36 ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
37 // 成功调用连接后,对返回数据进行的操作
38 public JSONObject handleResponse(final HttpResponse response)
39 throws ClientProtocolException, IOException {
40 int status = response.getStatusLine().getStatusCode();
41 if (status >= 200 && status < 300) {
42 // 获得调用成功后 返回的数据
43 HttpEntity entity = response.getEntity();
44 if (null != entity) {
45 String result = EntityUtils.toString(entity);
46 // 根据字符串生成JSON对象
47 JSONObject resultObj = JSONObject.fromObject(result);
48 return resultObj;
49 } else {
50 return null;
51 }
52 } else {
53 throw new ClientProtocolException("Unexpected response status: " + status);
54 }
55 }
56 };
57 // 返回的json对象
58 JSONObject responseBody = httpclient.execute(httpPost, responseHandler);
59 return responseBody;
60 } catch (Exception e) {
61 e.printStackTrace();
62 return null;
63 }
64 }
65
66 /**
67 * Base64解码
68 * @param str
69 * @return
70 */
71 public static String decode(String str) {
72 byte[] bt = null;
73 String s= "";
74 try {
75 sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
76 bt = decoder.decodeBuffer(str);