在國內使用電子地圖獲取到的經緯度都不是真實的經緯度,而是經過一定的算法在真實的經緯度上添加了一個偏移量,且不同的地圖有不同的算法。現在告訴大家在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); 77 s = new String(bt, "GB2312"); 78 } catch (IOException e) { 79 e.printStackTrace(); 80 } 81 return s; 82 } 83 }
三、運行上述代碼所需的jar包如下:
1、http://pan.baidu.com/s/1qX7Zipe 密碼:0rqq