作者:少伶围脖 | 来源:互联网 | 2024-10-25 19:00
通过采用JSON数据格式,能够高效且精确地获取用户的实时地理位置信息,为各类位置服务应用提供可靠的数据支持。该方法不仅简化了数据交换流程,还提高了地理信息处理的准确性和效率,适用于移动应用、导航系统及物联网设备等多种场景。
要改回可读格式,您也可以使用Geocoder,但有时由于Google Play服务问题而无法正常工作。我将这个json地理编码用作第二种选择,以防万一。
请参考 Google Geocoding
API
工作流程是通过您的纬度和经度并获取当前位置。请求网址将是这样。
String reqURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true";
希望这个答案对您有帮助。
public static JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
respOnse= client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getcontent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (Clientprotocolexception e) {
} catch (IOException e) {
}
JSONObject jsOnObject= new JSONObject();
try {
jsOnObject= new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
public static String getcurrentLocationViaJSON(double lat, double lng) {
JSONObject jsOnObj= getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
String street_address = null;
String postal_code = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i+ "," + results.length() ); //TODO delete this
do{
JSONObject r = results.getJSONObject(i);
JSONArray typesArray = r.getJSONArray("types");
String types = typesArray.getString(0);
if(types.equalsIgnoreCase("street_address")){
street_address = r.getString("formatted_address").split(",")[0];
Log.i("street_address", street_address);
}else if(types.equalsIgnoreCase("postal_code")){
postal_code = r.getString("formatted_address");
Log.i("postal_code", postal_code);
}
if(street_address!=null && postal_code!=null){
currentLocation = street_address + "," + postal_code;
Log.i("Current Location =>", currentLocation); //Delete this
i = results.length();
}
i++;
}while(i Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
return null;
}
根据我的经验, 会起作用。然后打电话
String currentLocation = getcurrentLocationViaJSON(lat, lng);