第一步 获取LocationManager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
第二部 获取可用的Location Provider
List providers =locationManager.getProviders(true);
if (providers.contains(LocationManager.GPS_PROVIDER)) {
provider =LocationManager.GPS_PROVIDER;
}else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
provider =LocationManager.NETWORK_PROVIDER;
}else {
Toast.makeText(this,"no location provider to use",Toast.LENGTH_SHORT).show();
return;
}
第三步 获取经纬度信息
Location location =locationManager.getLastKnownLocation(provider);
Log.d("location",location!=null?location.getLongitude()+"":"没有获取到地址信息");
if (location!=null){
showLocation(location);
}
locationManager.requestLocationUpdates(provider,5000,1,locationListener);
第四步 将获取到的经纬度信息逆地理编码为地址信息
HttpClient httpClient =new DefaultHttpClient();
HttpGet httpGet =new HttpGet(url.toString());
httpGet.setHeader("Accept-Language","zh-CN");
try {
HttpResponse response =httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() ==200){
HttpEntity entity =response.getEntity();
String response1 =EntityUtils.toString(entity,"utf-8");
response1 = response1.substring(29,response1.length()-1);
JSONObject jsonObject =new JSONObject(response1);
jsonObject = jsonObject.getJSONObject("result");
String address = jsonObject.getString("formatted_address");
Message message =new Message();
message.what =0 ;
message.obj =address;
handler.sendMessage(message);
}
private Handler handler =new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case 0:
String response = (String) msg.obj;
positionTextView.setText(response);
break;
default:
break;
}
}
};