android - 获取当前地址的最佳方式

时间:2014-01-30 10:24:10

标签: android geolocation

我从位置管理器获取纬度和经度。

获得这些积分之后,我正在尝试使用Geocoder方法获取地址,但我得到的IOException名为服务不可用

我试图解决这个问题,但我无法做到。然后我改变了实施,几个小时后我找到了一个解决方案,但我不知道这是最好的方法。

请告知获取当前地址的最佳方式是什么?

public class MainActivity extends Activity implements LocationListener {

 // providers
 public LocationManager locationManager;
 String strNetworkProvider;
 public TextView tvAddress;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // Get the Location Manager
   String locati
  locati getSystemService(location_context);
  strNetworkProvider = LocationManager.NETWORK_PROVIDER;
  locationManager.requestLocationUpdates(strNetworkProvider, 0, 0,
    MainActivity.this);
  tvAddress = (TextView) findViewById(R.id.address);
 }

 // Get the current Location
 @Override
 public void onLocationChanged(Location location) {
  if (location != null) {

   locationManager.removeUpdates(MainActivity.this);
   double latitude = location.getLatitude();
    double l
   Double[] geopoints = { latitude, longitude };
   Log.i("Latitude and Logitude", latitude + ", " + longitude);

   // async task for initial WS call
   new getAddressFromGeopoints().execute(geopoints);

  }
 }

 @Override
 public void onProviderDisabled(String arg0) {
 }

 @Override
 public void onProviderEnabled(String provider) {
 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {
 }

 // Async task for getting the address
 public class getAddressFromGeopoints extends
   AsyncTask<Double, Void, List<Address>> {

  @Override
  protected List<Address> doInBackground(Double... geoPoints) {
   List<Address> addresses;
   addresses = getFromLocation(geoPoints[0], geoPoints[1], 1);
   return addresses;
  }

  protected void onPostExecute(final List<Address> addresses) {
   if (addresses != null && addresses.size() > 0) {
    String address = addresses.get(0).getAddressLine(0);
    tvAddress.setText(address);
    Log.i("Address", address);
   }
  }
 }

 // This method is responsible for get the address from the
 // Geopoints(Latitude and Longitude)
 public static List<Address> getFromLocation(double lat, double lng,
   int maxResult) {

  String address = String
    .format(Locale.ENGLISH,
      "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language;="
        + Locale.getDefault().getCountry(), lat, lng);
  HttpGet httpGet = new HttpGet(address);
  HttpClient client = new DefaultHttpClient();
  HttpResponse response;
  StringBuilder stringBuilder = new StringBuilder();

  List<Address> retList = null;

  try {
    resp
   HttpEntity entity = response.getEntity();
   InputStream stream = entity.getContent();
   int b;
   while ((b = stream.read()) != -1) {
    stringBuilder.append((char) b);
   }

    JSONObject js JSONObject();
    js JSONObject(stringBuilder.toString());

   retList = new ArrayList<Address>();

   if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
    JSONArray results = jsonObject.getJSONArray("results");
    for (int i = 0; i < results.length(); i++) {
     JSONObject result = results.getJSONObject(i);
     String indiStr = result.getString("formatted_address");
     Address addr = new Address(Locale.ITALY);
     addr.setAddressLine(0, indiStr);
     retList.add(addr);
    }
   }

  } catch (ClientProtocolException e) {
   Log.e(MainActivity.class.getName(),
     "Error calling Google geocode webservice.", e);
  } catch (IOException e) {
   Log.e(MainActivity.class.getName(),
     "Error calling Google geocode webservice.", e);
  } catch (JSONException e) {
   Log.e(MainActivity.class.getName(),
     "Error parsing Google geocode webservice response.", e);
  }

  return retList;
 }
}

1 个答案:

答案 0 :(得分:0)

分享我一般使用的代码

如何使用代码: - 首先计算lat和lng以及调用String address[] = getCountry();

address[0] // country
address[1] // postal code
address[2] // Locality
address[3] // AddressLine

常量

    private static final int COUNTRY = 0;
    private static final int POSTALCODE = 1;
    private static final int CITY = 2;
    private static final int ADDRESS = 3;

方法

public String[] getCountry() {

    if (lat != 0.0 && lng != 0.0) {
        Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
        String[] country = new String[4];
        try {

            List<Address> addresses = geocoder.getFromLocation(lat,
                    lng, 1);

            if (addresses.size() > 0) {
                Address obj = addresses.get(0);
                // String add = obj.getAddressLine(0);

                country[0] = obj.getCountryName() == null ? "xx" : obj
                        .getCountryName();
                country[1] = obj.getPostalCode() == null ? "xx" : obj
                        .getPostalCode();
                country[2] = obj.getLocality() == null ? "xx" : obj
                        .getLocality();
                country[3] = obj.getAddressLine(0) == null ? "xx" : obj
                        .getAddressLine(0);
            } else {

                country = getFromLocation();

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            // Toast.makeText(activity, e.getMessage(),
            // Toast.LENGTH_SHORT).show();

            return getFromLocation();

        }
        return country;
    } else {
        return new String[] { "xx", "xx", "xx", "xx" };
    }
}

public String[] getFromLocation() {

    String[] countries = new String[4];
    String address = String
            .format(Locale.ENGLISH,
                    "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
                            + Locale.getDefault().getCountry(), lat,
                    lng);

    // Log.v("url", address);

    StringBuilder stringBuilder = new StringBuilder();

    try {
        URL url = new URL(address);
        HttpURLConnection conn = (HttpURLConnection) url
                .openConnection();

        InputStream stream = conn.getInputStream();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }

        JSONObject jsonObject = new JSONObject(stringBuilder.toString());

        // Log.v("json", stringBuilder.toString());
        if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
            JSONArray results = jsonObject.getJSONArray("results");
            int count = 0;
            for (int i = 0; i < results.length(); i++) {
                JSONObject result = results.getJSONObject(i);
                countries[ADDRESS] = result
                        .getString("formatted_address");
                JSONArray array = result
                        .getJSONArray("address_components");
                for (int j = 0; j < array.length(); j++) {
                    JSONObject oo = array.getJSONObject(j);
                    JSONArray type = oo.getJSONArray("types");

                    for (int k = 0; k < type.length(); k++) {

                        String tt = type.getString(k);

                        if (tt.equals("country")) {
                            countries[COUNTRY] = oo
                                    .getString("long_name");
                            count++;
                        }
                        if (tt.equals("postal_code")) {
                            countries[POSTALCODE] = oo
                                    .getString("long_name");
                            count++;
                        }
                        if (tt.equals("locality")) {
                            countries[CITY] = oo.getString("long_name");
                            count++;
                        }

                        if (count == 3) {
                            return countries;
                        }

                    }

                }
                String indiStr = result.getString("address_components");
                Address addr = new Address(Locale.getDefault());

                addr.setAddressLine(0, indiStr);
            }
        }

    } catch (ClientProtocolException e) {
        Log.e(MainActivity.class.getName(),
                "Error calling Google geocode webservice.", e);

        return new String[] { "xx", "xx", "xx", "xx" };
    } catch (IOException e) {
        Log.e(MainActivity.class.getName(),
                "Error calling Google geocode webservice.", e);
        return new String[] { "xx", "xx", "xx", "xx" };
    } catch (JSONException e) {
        Log.e(MainActivity.class.getName(),
                "Error parsing Google geocode webservice response.", e);
        return new String[] { "xx", "xx", "xx", "xx" };
    }

    return countries;
}

}

如果代码找不到地址,则会返回xx