android - 反向地理编码在某些 Android 设备上不起作用?

标签 android google-maps google-geocoder

我在 map 上开发一个应用程序,我无法在这个手机上获取地址,它的 android 版本是 4.3,如下所示 --

example

但它在我的手机上运行良好,它的版本是 4.1.2,如下所示 --

example

它在某些 Lollipop 版本中运行良好。

    final Geocoder gc = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = gc.getFromLocation(lat, lng, 1);
        StringBuilder sb = new StringBuilder();
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                if (address.getAddressLine(i).equals("null")) {

                } else {
                    sb.append(address.getAddressLine(i)).append("\n");
                    sb.append(address.getLocality()).append("\n");
                    //sb.append(address.getPostalCode()).append("\n");
                    //sb.append(address.getCountryName());
                }
            }
           // Toast.makeText(RegistrationTest.this, "Text Address is " + sb.toString(), Toast.LENGTH_SHORT).show();
            text_address = sb.toString();
        }
    } catch (Exception e) {
        //Toast.makeText(RegistrationTest.this, "exception " + e, Toast.LENGTH_SHORT).show();
    }

抱歉我的英语不好,感谢您的时间和帮助!

请帮帮我,我卡在这里了!

最佳答案

地理编码器在某些设备上不工作。因此,我们需要创建一个自定义地理编码器。您可以使用 Geocoder.isPresent() 检查 Geocoder 是否由设备制造商实现但该方法不可靠。我们无法确保使用它实现 Geocoder。

对于自定义 Geocoder,您可以使用以下类,其用法与使用 Geocoder 完全相同:

import android.location.Address;
import android.util.Log;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyGeocoder {

  public static final String TAG = MyGeocoder.class.getSimpleName();

  static OkHttpClient client = new OkHttpClient();

  public static List<Address> getFromLocation(double lat, double lng, int maxResult) {

    String address = String.format(Locale.US,
        "https://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=false&language="
            + Locale.getDefault().getCountry(), lat, lng);
    Log.d(TAG, "address = " + address);
    Log.d(TAG, "Locale.getDefault().getCountry() = " + Locale.getDefault().getCountry());

    return getAddress(address, maxResult);

  }

  public static List<Address> getFromLocationName(String locationName, int maxResults)  {

    String address = null;
    try {
      address = "https://maps.google.com/maps/api/geocode/json?address=" + URLEncoder.encode(locationName,
          "UTF-8") + "&ka&sensor=false";
      return getAddress(address, maxResults);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return null;
  }

  private static List<Address> getAddress(String url, int maxResult) {
    List<Address> retList = null;

    Request request = new Request.Builder().url(url)
        .header("User-Agent", "OkHttp Headers.java")
        .addHeader("Accept", "application/json; q=0.5")
        .build();
    try {
      Response response = client.newCall(request).execute();
      String responseStr = response.body().string();
      JSONObject jsonObject = new JSONObject(responseStr);

      retList = new ArrayList<Address>();

      if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
        JSONArray results = jsonObject.getJSONArray("results");
        if (results.length() > 0) {
          for (int i = 0; i < results.length() && i < maxResult; i++) {
            JSONObject result = results.getJSONObject(i);
            Address addr = new Address(Locale.getDefault());

            JSONArray components = result.getJSONArray("address_components");
            String streetNumber = "";
            String route = "";
            for (int a = 0; a < components.length(); a++) {
              JSONObject component = components.getJSONObject(a);
              JSONArray types = component.getJSONArray("types");
              for (int j = 0; j < types.length(); j++) {
                String type = types.getString(j);
                if (type.equals("locality")) {
                  addr.setLocality(component.getString("long_name"));
                } else if (type.equals("street_number")) {
                  streetNumber = component.getString("long_name");
                } else if (type.equals("route")) {
                  route = component.getString("long_name");
                }
              }
            }
            addr.setAddressLine(0, route + " " + streetNumber);

            addr.setLatitude(
                result.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
            addr.setLongitude(
                result.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
            retList.add(addr);
          }
        }
      }
    } catch (IOException e) {
      Log.e(TAG, "Error calling Google geocode webservice.", e);
    } catch (JSONException e) {
      Log.e(TAG, "Error parsing Google geocode webservice response.", e);
    }

    return retList;
  }
}

关于android - 反向地理编码在某些 Android 设备上不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332594/

相关文章:

android - 发送带附件的电子邮件时出错

javascript - 找到一种使用 Google Maps API 通过回调传递信息的好方法

javascript - 谷歌不会恢复当前位置的当前纬度和经度

尽管随用随付,但 r ggmap 地理编码查询超出了最大值?

android - 在 Fragment 级别应用的滑动手势以及禁用默认滑动的 ViewPager

java - "debuggable false"足以阻止调试我的应用程序吗?

android - fragment 中的 getMapAsync()

javascript - Google Maps Draw -- 通过拖动绘制线或多边形

python - TypeError : float() argument must be a string or a number, 不是 'method'

android - Eclipse FindBugs 插件因 Android 项目要求 java.rmi.remote 而失败