Pregunta

Intento obtener el código postal actual de la longitud y la latitud que myLocationOverlay ofrece y establecer esto en una vista de edición de mi actividad.

La actividad se bloquea cuando trato de obtener la longitud y la latitud de MyLocationOverlay.

¿Qué pasa con este código?

Saludos, flotador

Salida de LogCat: http://codepaste.net/vs6itk La línea 59 es la siguiente línea:

 double currentLatitude = myLocationOverlay.getMyLocation().getLatitudeE6(); 

Aquí está mi código:

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.partner_suche);

    final EditText tView = (EditText) findViewById(R.id.editTextPLZ);
    final MapView mView = (MapView) findViewById(R.id.mapview);
    mView.getController().setZoom(14);

    List<Overlay> mapOverlays = mView.getOverlays();

    myLocationOverlay = new MyCustomLocationOverlay(this, mView);
    mapOverlays.add(myLocationOverlay);
    myLocationOverlay.enableMyLocation();
    myLocationOverlay.enableCompass();
    myLocationOverlay.runOnFirstFix(new Runnable() {
        public void run() {
            mView.getController().animateTo(myLocationOverlay.getMyLocation());
        }
    });

    Geocoder gc = new Geocoder(this, Locale.getDefault());
    double currentLatitude = myLocationOverlay.getMyLocation().getLatitudeE6();
    double currentLongitute = myLocationOverlay.getMyLocation().getLongitudeE6();

    try 
    {
        List<Address> addresses = gc.getFromLocation(currentLatitude, currentLongitute, 1);
        if (addresses.size() > 0) 
        {
            tView.setText(addresses.get(0).getLocality());
        }
    } catch (IOException e) 
    {

    }
}

EDITAR: Creé un LocationListener para obtener mi ubicación actual. Ahora la parte se bloquea donde trato de ejecutar gc.getFromLocation (latitud, longitud, 1); ¿No puedo leer la excepción? :/

LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);
    String provider = LocationManager.GPS_PROVIDER;

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
            } 

        public void onProviderDisabled(String provider){
            updateWithNewLocation(null);
            }
        public void onProviderEnabled(String provider){ }
        public void onStatusChanged(String provider, int status,Bundle extras){ }
        };

    locationManager.requestLocationUpdates(provider, 0, 0, locationListener);

private void updateWithNewLocation(Location location) {
    final EditText tView = (EditText) findViewById(R.id.editTextPLZ);
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();

    Geocoder gc = new Geocoder(this, Locale.getDefault());
    if (location != null) {
        try 
        {
            List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
            if (addresses.size() > 0) 
            {
                Address address = addresses.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
                    tView.setText(address.getPostalCode());
                }
            }
        } catch (Exception e) 
        {

        }
    }

}
¿Fue útil?

Solución

Si está utilizando un emulador API de nivel 8 o 9 y obteniendo la excepción:

java.io.ioexception: servicio no disponible

Entonces es un error conocido, ver servicio no disponible

Sin embargo, funciona bien en dispositivos reales y nivel de emulador 7. (Probablemente debería poner una trampa en las direcciones que también son nulas, ¡aunque esto no hará que el geocoder funcione!)

Otros consejos

Probablemente la ubicación que se devuelve desde

myLocationOverlay.getMyLocation()

o

Location location = locationManager.getLastKnownLocation(provider);

es nulo. Probablemente debido a que su aplicación aún no ha recibido una solución de ubicación y no tiene ubicaciones previamente guardadas.

Intente mover el bloque de código donde realice la geocodificación en su ejecución que se ejecuta después de recibir una solución. Como esto:

myLocationOverlay.runOnFirstFix(new Runnable() {
    public void run() {
        Location loc = myLocationOverlay.getMyLocation();
        if (loc != null) {
            mView.getController().animateTo(loc);
            Geocoder gc = new Geocoder(this, Locale.getDefault());
            double currentLatitude = loc.getLatitudeE6();
            double currentLongitute = loc.getLongitudeE6();

            try 
            {
                List<Address> addresses = gc.getFromLocation(currentLatitude, currentLongitute, 1);
                if (addresses.size() > 0) 
                {
                    tView.setText(addresses.get(0).getLocality());
                }
            } catch (IOException e) 
            {

            }
        }
    }
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top