Search code examples
javaandroidgpslocationmanager

Determining a country by GPS coordinates


I have some GPS coordinates powered by LocationManager. When device connects to internet I must check in which country I have been. Are there any services that allows you to send an GPS location and receive a country in response?


Solution

  • You can use this to get all the details that are stored as address in the given Longitude and Latitude.

    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), true);
    
    Location locations = locationManager.getLastKnownLocation(provider);
    List<String>  providerList = locationManager.getAllProviders();
    if(null!=locations && null!=providerList && providerList.size()>0){                 
    double longitude = locations.getLongitude();
    double latitude = locations.getLatitude();
    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());                 
    try {
        List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
        if(null!=listAddresses&&listAddresses.size()>0){
            String _Location = listAddresses.get(0).getAddressLine(0);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    }
    

    If you need more details for the Longitude and Latitude, You can you this,

    public void getAddress(double lat, double lng) {
        Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
            Address obj = addresses.get(0);
            String add = obj.getAddressLine(0);
            GUIStatics.currentAddress = obj.getSubAdminArea() + ","
                    + obj.getAdminArea();
            GUIStatics.latitude = obj.getLatitude();
            GUIStatics.longitude = obj.getLongitude();
            GUIStatics.currentCity= obj.getSubAdminArea();
            GUIStatics.currentState= obj.getAdminArea();
            add = add + "\n" + obj.getCountryName();
            add = add + "\n" + obj.getCountryCode();
            add = add + "\n" + obj.getAdminArea();
            add = add + "\n" + obj.getPostalCode();
            add = add + "\n" + obj.getSubAdminArea();
            add = add + "\n" + obj.getLocality();
            add = add + "\n" + obj.getSubThoroughfare();
    
            Log.v("IGA", "Address" + add);
            // Toast.makeText(this, "Address=>" + add,
            // Toast.LENGTH_SHORT).show();
    
            // TennisAppActivity.showDialog(add);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    

    Don't forget to add the permissions in the manifest file.