Geocoder.getFromLocation java.io.IOException: Service not Available

 

      A class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.

 

https://developers.google.com/maps/documentation/geocoding/

 

http://stackoverflow.com/questions/9272918/service-not-available-in-geocoder

 

 

package com.example.android.location;

 

import java.util.List;

import java.util.Locale;

 

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.BasicResponseHandler;

import org.json.JSONArray;

import org.json.JSONObject;

 

import android.annotation.SuppressLint;

import android.content.Context;

import android.location.Address;

import android.location.Geocoder;

import android.location.Location;

import android.net.http.AndroidHttpClient;

import android.os.AsyncTask;

import android.util.Log;

 

public class GeocoderHelper {

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

 

    private boolean running = false;

 

    @SuppressLint("NewApi")

    public void fetchCityName(final Context contex, final Location location) {

        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=zh-CN";

 

                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;

 

                                    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);

                }

            };

        }.execute();

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值