android中的位置管理器得到错误的结果

时间:2013-11-23 22:43:31

标签: android

我正在编写android代码以获取当前位置并转换lat,很长时间来解决但是我得到了错误的结果,

问题在于:

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
          System.out.println("Provider " + provider + " has been selected.");
          onLocationChanged(location);
          Log.d("msgh","msgh");
        } else {
             System.out.println("location not available");
            Log.d("msg","msg");
        }

代码始终输入else语句

1 个答案:

答案 0 :(得分:0)

试试这个有效的

private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeoCoderHelper.class.getName());

private boolean running = false;

public interface CityListener {

    public void cityNameListener(String s);

}

public void fetchCityName(final Context contex, final Location location,final CityListener listener)
{
    if (running)
        return;

    new AsyncTask<Void, Void, String>()
    {
        protected void onPreExecute()
        {
            running = true;
        };

        @Override
        protected String doInBackground(Void... params)
        {
            String cityName = null;

            if (Geocoder.isPresent())
            {
                try
                {
                    Geocoder geocoder = new Geocoder(contex, Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                    if (addresses.size() > 0)
                    {
                        cityName = addresses.get(0).getLocality();
                    }
                }
                catch (Exception ignored)
                {
                    // after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
                }
            }

            if (cityName != null) // i.e., Geocoder succeed
            {
                return cityName;
            }
            else // i.e., Geocoder failed
            {
                return fetchCityNameUsingGoogleMap();
            }
        }

        // Geocoder failed :-(
        // Our B Plan : Google Map
        private String fetchCityNameUsingGoogleMap()
        {
            String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + location.getLatitude() + ","
                    + location.getLongitude() + "&sensor=false&language=fr";

            try
            {
                JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
                        new BasicResponseHandler()));

                // many nested loops.. not great -> use expression instead
                // loop among all results
                JSONArray results = (JSONArray) googleMapResponse.get("results");
                for (int i = 0; i < results.length(); i++)
                {
                    // loop among all addresses within this result
                    JSONObject result = results.getJSONObject(i);
                    if (result.has("address_components"))
                    {
                        JSONArray addressComponents = result.getJSONArray("address_components");
                        // loop among all address component to find a 'locality' or 'sublocality'
                        for (int j = 0; j < addressComponents.length(); j++)
                        {
                            JSONObject addressComponent = addressComponents.getJSONObject(j);
                            if (result.has("types"))
                            {
                                JSONArray types = addressComponent.getJSONArray("types");

                                // search for locality and sublocality
                                String cityName = null;
                                String countyName = null ;

                                for (int k = 0; k < types.length(); k++)
                                {
                                    if ("locality".equals(types.getString(k)) && cityName == null)
                                    {
                                        if (addressComponent.has("long_name"))
                                        {
                                            cityName = addressComponent.getString("long_name");
                                        }
                                        else if (addressComponent.has("short_name"))
                                        {
                                            cityName = addressComponent.getString("short_name");
                                        }
                                    }
                                    if ("sublocality".equals(types.getString(k)))
                                    {
                                        if (addressComponent.has("long_name"))
                                        {
                                            cityName = addressComponent.getString("long_name");
                                        }
                                        else if (addressComponent.has("short_name"))
                                        {
                                            cityName = addressComponent.getString("short_name");
                                        }
                                    }
                                }
                                if (cityName != null)
                                {
                                    return cityName;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ignored)
            {
                ignored.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String cityName)
        {
            running = false;
            if (cityName != null)
            {
                // Do something with cityName
                Log.i("GeocoderHelper", cityName);
                listener.cityNameListener(cityName);
            }
        };
    }.execute();
}

你可以像这样打电话

new GeoCoderHelper().fetchCityName(this,location,new GeoCoderHelper.CityListener() {
        @Override
        public void cityNameListener(String s) {
            addressCityTextView.setText(s);
        }
    });