GPS android - получение широты и долготы

1

Можете ли вы помочь мне в этом.. приложение начало сбой, когда я добавил геокодер, чтобы получить название города, используя широту и долготу.

    double latitude, longitude;
    private TextView lala;

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    longitude = location.getLongitude();
    latitude = location.getLatitude();
    final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            longitude = location.getLongitude();
            latitude = location.getLatitude();
        }

        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub

        }

        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub

        }

        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub

        }
    };

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
    lala = (TextView) findViewById(R.id.textView1);

    Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
    List<Address> myList = null;
    try {
        myList = myLocation.getFromLocation(latitude, longitude, 1);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


    lala.setText((CharSequence) myList);
  • 0
    Stacktrace, пожалуйста?
Теги:
geolocation

2 ответа

8
Лучший ответ

lm.getLastKnownLocation может возвращать значение null, а затем tou try to getLongitude() вы получите NullPointerException

Также lala.setText((CharSequence) myList); может сделать то же самое (throw Exception), потому что myList может быть здесь null (если Geocoder не работает).

ИЗМЕНИТЬ Для устранения исключения в Geocoder рассмотрите следующий контрольный список

  • Убедитесь, что ваша широта и долгота не являются нулевыми.
  • Убедитесь, что -90 <= широта <= 90 и -180 <= longitude <= 180
  • Убедитесь, что у вас есть доступное сетевое подключение.

EDIT2 Улучшенный код

private TextView lala;

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if(location != null) {
    showMyAddress(location);
}

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

    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }
};

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
lala = (TextView) findViewById(R.id.textView1);



// Also declare a private method

private void showMyAddress(Location location) {
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
    List<Address> myList;
    try {
        myList = myLocation.getFromLocation(latitude, longitude, 1);
        if(myList.size() == 1) {
            lala.setText(myList.get(0).toString());             
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
  • 0
    Вы правы .. но можете ли вы сказать мне, что нужно сделать, чтобы геокодер не потерпел неудачу .. Извините, я новичок в Android и Java ..
  • 0
    Я отредактировал свой ответ
Показать ещё 3 комментария
2
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
int la = (int) (location.getLatitude() * 1E6);
int lo = (int) (location.getLongitude() * 1E6);

Ещё вопросы

Сообщество Overcoder
Наверх
Меню