Android Geocoder si comporta in modo diverso su alcuni dispositivi

voti
0

Ho il codice qui sotto, funziona perfettamente su alcuni dispositivi e in altri la funzione di getFromLocationName restituire una lista con il formato 0.

Ad esempio, nel Nexus 6prestituisce il risultato corretto e Meizu MX5restituisce una lista con il formato 0.

Ho le stesse autorizzazioni e GPS consentono per entrambi i dispositivi. Versione Android sul Nexus 6pè 7.1.2 e Meizu MX5è 5.1

  Geocoder geocoder = new Geocoder(context);
  List<Address> addresses = geocoder.getFromLocationName(place, 3);

Note :

  1. posto è la posizione che l'utente è entrato (String).
  2. Geocoder è da android.location.Geocoder;

Allora, perché la differenza? E 'legato alla versione di Android sui dispositivi?

È pubblicato 02/11/2017 alle 07:58
fonte dall'utente
In altre lingue...                            


1 risposte

voti
2

Geocoder in Android è in realtà non hanno lo stesso comportamento su tutti i dispositivi. Ho testato il Geocoder con i seguenti dispositivi:

  • Samsung (Android 4.4 e 5.1)
  • Lenovo (Android 5.0)
  • Vivo (Android 6.0.1)
  • Andromax (Android 5.1.1)
  • Xiaomi (Android 5.1)

Tutti i dispositivi di tornare nella lista, ma Xiaomi, restituisce zero liste. Quindi, non possiamo dipendere da Geocoder. La soluzione è quella di creare la nostra applicazione Geocoder utilizzando Google Geocoding API e utilizzarlo ogni volta che la lista restituisce 0.

Ecco l'attuazione di Geocoder (ho trovato da SO, ma non ricordo la fonte) che può essere utilizzato ricade perfettamente come usare il 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;
  }
}

Essere consapevoli della quota giornaliera, che non è accaduto in Geocoder Android API.

Risposto il 02/11/2017 a 10:18
fonte dall'utente

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more