使用LocationManager和GeoCoder返回null的地址

时间:2014-02-13 04:27:48

标签: java android locationmanager

我只是试图抓住用户位置(最准确的方式,我假设GPS) - 并将latittude / longitutde转换为地址以显示在EditText中。我不断得到“null - UnitedStates - US - 06705”。任何的想法?这是我的代码:

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        providers = locationManager.getBestProvider(criteria, false);
        locationManager.requestLocationUpdates(providers, 5000,0, this);

onLocationChanged方法

@Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (location != null)
        {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Log.i(mTAG, String.valueOf(latitude));

            try {
                 geoCoder = new Geocoder(this);

                 addresses = geoCoder.getFromLocation(latitude, longitude, 1);
                 StringBuilder str = new StringBuilder();
                 if (geoCoder.isPresent()) {


                 Address returnAddress = addresses.get(0);

                 String localityString = returnAddress.getLocality();
                 String city = returnAddress.getCountryName();
                 String region_code = returnAddress.getCountryCode();
                 String zipcode = returnAddress.getPostalCode();

                 str.append(localityString + " - ");
                 str.append(city + " - " + region_code + " - ");
                 str.append(zipcode);

                 addressTxtField.setText(str);
                 Toast.makeText(getApplicationContext(), str,
                 Toast.LENGTH_SHORT).show();
                 }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

1 个答案:

答案 0 :(得分:0)

您在此处请求最后的已知位置。如果有任何其他应用请求位置,这是一个位置。如果没有app请求位置坐标,那么它将返回null。你必须提出请求locationManager.requestLocationUpdates.

在代码中尝试:

locationManager.requestLocationUpdates(provider, 5000,0, this);

实现android.location.LocationListener接口,然后仅覆盖位置更改方法。

//called when user location changed
    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub
        myLocation = new LatLng(arg0.getLatitude(),arg0.getLongitude());
        Log.d("location","in location changed");
    }