首页 新闻 会员 周边

Android反向地理编码显示不出来!

0
悬赏园豆:20 [已解决问题] 解决于 2017-01-05 16:57

我用google 的Geocoding API 接口来处理反向地理编码 ,但是运行时是空白界面,显示不出位置  下面是代码 ,请告诉我怎么办

public class MainActivity extends Activity {
public static final int SHOW_LOCATION=0;
private TextView positionTextView;
private LocationManager locationManager;
private String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
positionTextView=(TextView) findViewById(R.id.position_text_view);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//获取所有可用的位置提供器
List<String> providerList=locationManager.getProviders(true);
if(providerList.contains(locationManager.GPS_PROVIDER)){
provider=locationManager.GPS_PROVIDER;
}else if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
provider=LocationManager.NETWORK_PROVIDER;
}else{
//当没有可用的位置提供器时,弹出Toast提示用户
Toast.makeText(this, "No location Provider to use", Toast.LENGTH_SHORT).show();
return;
}
Location location=locationManager.getLastKnownLocation(provider);
if(location!=null){
//显示当前设备的位置信息
showLocation(location);
}
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);


}
protected void onDestroy(){
super.onDestroy();
if(locationManager!=null){
//关闭程序时将监听器移除
locationManager.removeUpdates(locationListener);
}
}
LocationListener locationListener=new LocationListener(){
@Override
public void onStatusChanged(String provider,int status,Bundle extras){

}
@Override
public void onProviderEnabled(String provider){}
@Override
public void onProviderDisabled(String provider){}
@Override
public void onLocationChanged(Location location){
//更新当前设备的位置信息
showLocation(location);
}
};

private void showLocation(final Location location){
//String currentPosition="latitude is"+location.getLatitude()+"\n"+
//"longitude is"+location.getLongitude();
// positionTextView.setText(currentPosition);
new Thread(new Runnable(){
@Override
public void run(){
try{
//组装反向地理编码的接口地址
StringBuilder url=new StringBuilder();
url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
url.append(location.getLatitude()).append(",");
url.append(location.getLongitude());
url.append("&sensor=false");
HttpClient httpclient=new DefaultHttpClient();
HttpGet httpget=new HttpGet(url.toString());
//在请求消息头中指定语言,保证服务器会返回中文数据
httpget.addHeader("Accept-Language","zh-CN");
HttpResponse httpResponse=httpclient.execute(httpget);
if(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity,"utf-8");
JSONObject jsonObject=new JSONObject(response);
//获取results节点下的位置信息
JSONArray resultArray=jsonObject.getJSONArray("results");
if(resultArray.length()>0){
JSONObject subObject=resultArray.getJSONObject(0);
//取出格式化后的位置信息
String address=subObject.getString("formatted_address");
Message message=new Message();
message.what=SHOW_LOCATION;
message.obj=address;
handler.sendMessage(message);
}
}

}catch(Exception e){
e.printStackTrace();
}
}
}).start();

}
private Handler handler=new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case SHOW_LOCATION:
String currentPosition=(String) msg.obj;
positionTextView.setText(currentPosition);
break;
default:
break;

}
}
};

}

 

天码也行空的主页 天码也行空 | 初学一级 | 园豆:186
提问于:2016-11-20 20:01
< >
分享
最佳答案
0

第一步: compile 'com.google.android.gms:play-services:10.0.1' 

第二步: 加入Android6.0权限验证

第三步: 获取到经纬度后调用谷歌的接口 

 

public class FetchAddressIntentService extends IntentService{
    private RxManager rxManager;
    private PreferenceUtil prefUtil;
    private Geocoder geocoder;

    public FetchAddressIntentService() {
        super("FetchAddressIntentService");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        geocoder = new Geocoder(this, Locale.getDefault());
        prefUtil = new PreferenceUtil(this);
        rxManager = new RxManager();
        super.onStart(intent, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String errorMessage = "service not available";
        try {
            LogUtil.d("------------getDetailAddress-------------lat="+prefUtil.getLastLocationLAT() + ", lng="+prefUtil.getLastLocationLNG());
            List<Address> addresses = geocoder.getFromLocation(prefUtil.getLastLocationLAT(), prefUtil.getLastLocationLNG(), 1);
            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                LogUtil.d("--------getDetailAddress-------success------------");
                RxBus.getInstance().post(Constant.RXBUS_GOT_LOCATION_SUCCEED, address);
                errorMessage = "";
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (IllegalArgumentException illegalArgumentException) {
            illegalArgumentException.printStackTrace();
        }
        if (!errorMessage.isEmpty()) {
            LogUtil.d("------getDetailAddress---------fail------------");
            rxManager.post(Constant.RXBUS_GOT_LOCATION_SUCCEED, null);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        rxManager.clear();
        LogUtil.d("------onDestroy------");
    }

 

再多说几句, 在API<21时,你用LocationManager可以通过wifi获取经纬度,但是在之后就不能获取了,需要使用GoogleApiClient来获取,详细参照官方, 其次是GPS获取经纬度的条件不大容易满足,空旷的地方。这里有个第三方库作为参考。

收获园豆:20
zeroonec | 初学一级 |园豆:59 | 2017-01-05 15:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册