通過經緯度獲取地理位置資訊
阿新 • • 發佈:2019-02-01
最近做一個車載裝置app,裝置獲取北斗gps資料上傳的到後臺,app通過後臺提供的經緯度反取地理編碼位置,支援Google和百度。
獲取地理位置url
//Google
public String getGoogleUrl(boolean isCn, String longitude,String latitude) {
if (!isCn) {
return "http://maps.google.com/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=false&language="
+ Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry();
} else {
return "http://ditu.google.cn/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=false&language="
+ Locale.getDefault().getLanguage() + "-" + Locale.getDefault(). getCountry();
}
}
//百度,到百度地圖獲取ak金鑰
public String getBaiduUrl(String longitude,String latitude) {
return "http://api.map.baidu.com/geocoder/v2/?" +
"ak=ahH7ICSO020gfifmGVog5OTimwq" +
"&mcode=DC:B1:26:FF:66:49:62:85:98:16:AE:2A:E8:69:A9:EE:AC:14:3B;com.icar.taxi" +
"&output=json" +
"&pois=0&location="+latitude+","+longitude;
}
獲取詳細街道地址
/**
* @return 詳細街道地址
*/
public String getAddress(String url){
//定義一個HttpClient,用於向指定地址傳送請求
HttpClient client = new DefaultHttpClient();
//向指定地址傳送Get請求
HttpGet hhtpGet = new HttpGet(url);
StringBuilder sb = new StringBuilder();
try {
//獲取伺服器響應
HttpResponse response = client.execute(hhtpGet);
HttpEntity entity = response.getEntity();
if(entity !=null){
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"),8192);
String line =null;
while ((line= reader.readLine())!=null){
sb.append(line +"\n");
}
reader.close();
}
//將伺服器返回的字串轉換為JSONObject 物件
JSONObject jsonObject = new JSONObject(sb.toString());
//從JSONObject 中取出location 屬性
if (AppConfig.mapType()) {
return jsonObject.optJSONObject("result").optString("formatted_address");
} else {
return jsonObject.optJSONArray("results").optJSONObject(0).optString("formatted_address");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}