Не получается название страны по широте и долготе - PullRequest
0 голосов
/ 07 апреля 2020

Я хочу получить название страны из местоположения пользователя, поэтому для этой цели я нахожу широту и долготу текущего местоположения. Теперь я хочу получить название страны от этого лат и лонги. Но проблема в том, что я не получаю название страны, не знаю, почему, пожалуйста, проверьте мой код и помогите мне.

HomeActivity. java:

if (checkPermissions()) {
        if (isLocationEnabled()) {
            mFusedLocationClient.getLastLocation().addOnCompleteListener(
                    new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            Location location = task.getResult();
                            if (location == null) {
                                requestNewLocationData();
                            } else {
                                lat = location.getLatitude();   //here i am getting latitude and logitude value
                                lon = location.getLongitude();
                            }
                        }
                    }
            );
        } else {
            Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    } else {
        requestPermissions();
    }
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address>addresses;
    try{
        addresses = geocoder.getFromLocation(lat, lon, 10);
        if(addresses.size()>0){
            for(Address adr: addresses){
                if(adr.getCountryName()!= null && adr.getCountryName().length()>0){
                    countryname = adr.getCountryName();  
                    latlocation.setText(countryname); //but here country name is showing nothing.

                    break;
                }
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }

Пожалуйста, помогите мне.

Ответы [ 2 ]

0 голосов
/ 07 апреля 2020
SingleLocationProvider class


public class SingleShotLocationProvider {
public static interface LocationCallback { public void onNewLocationAvailable(GPSCoordinates location);
}

// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {

    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (isNetworkEnabled) {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        try {


            locationManager.requestSingleUpdate(criteria, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            }, null);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else {
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            locationManager.requestSingleUpdate(criteria, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            }, null);
        }
    }
}


// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
    public float longitude = -1;
    public float latitude = -1;

    public GPSCoordinates(float theLatitude, float theLongitude) {
        longitude = theLongitude;
        latitude = theLatitude;
    }

    public GPSCoordinates(double theLatitude, double theLongitude) {
        longitude = (float) theLongitude;
        latitude = (float) theLatitude;
    }
}

}

used SingleLocationProvider for getting location and then used geocoder for getting address

SingleShotLocationProvider.requestSingleUpdate(activity,
                new SingleShotLocationProvider.LocationCallback() {
                    @Override
                    public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
                        Log.d("Location", "my location is " + location.toString());

                        latitude = location.latitude;
                        longitude = location.longitude;

                        Geocoder coder = new Geocoder(activity);
                        List<Address> address;

                        try {
                            address = coder.getFromLocation(latitude,longitude, 5);
                            if (address != null) {
                                Address address1 = address.get(0);
                              String country= addresses.get(0).getCountryName();
                            }


                        } catch (Exception e) {
                            e.printStackTrace();

                        }



                    }
                });
0 голосов
/ 07 апреля 2020

Получить страну или другую строку из адреса, как показано ниже код

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());

addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...