How to get complete address from latitude and longitude?

前端 未结 21 2079
深忆病人
深忆病人 2020-11-22 09:07

I want to get following values from Latitude and Longitude in android

  1. Street Address
  2. City / State
  3. Zip
  4. Complete Address
<
相关标签:
21条回答
  • 2020-11-22 09:40

    You can create class

    public class GeoLocation {
    
    private Context mContext;
    
    private String mLatitude;
    private String mLongtitude;
    private String mStreet;
    private String mHouseNumber;
    private String mPostalCode;
    private String mCity;
    
    private Location mMarkerLocation;
    
    public GeoLocation (Context context) {
        mContext = context;
    }
    
    public String getStreet () {
        return mStreet;
    }
    
    public String getHouseNumber () {
        return mHouseNumber;
    }
    
    public String getPostalCode () {
        return mPostalCode;
    }
    
    public String getCity () {
        return mCity;
    }
    
    public String getLatitude () {
        return mLatitude;
    }
    
    public String getLongtitude () {
        return mLongtitude;
    }
    
    // Lookup address via reverse geolocation
    // Call this one
    public void lookUpAddress (Location markerLocation) {
        mMarkerLocation = markerLocation;
        if (Geocoder.isPresent()) {
            (new GetAddressTask(mContext)).execute();
        }
    }
    
    public class GetAddressTask extends AsyncTask<android.location.Location, Void, String> {
    
        public GetAddressTask (Context context) {
            super();
            mContext = context;
        }
    
        @Override
        protected String doInBackground (android.location.Location... params) {
            Geocoder geocoder =
                    new Geocoder(mContext, Locale.getDefault());
            android.location.Location location = params[0];
    
            List<Address> addresses = null;
            try {
                if (mMarkerLocation != null) {
                    addresses = geocoder.getFromLocation(mMarkerLocation.getLatitude(),
                            mMarkerLocation.getLongitude(), 1);
                }
            } catch (IOException exception) {
                Log.e("ComplaintLocation",
                        "IO Exception in getFromLocation()", exception);
    
                return ("IO Exception trying to get address");
            } catch (IllegalArgumentException exception) {
                String errorString = "Illegal arguments " +
                        Double.toString(location.getLatitude()) + " , " +
                        Double.toString(location.getLongitude()) + " passed to address service";
                Log.e("LocationSampleActivity", errorString, exception);
    
                return errorString;
            }
    
            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
    
                if (address.getMaxAddressLineIndex() > 0) {
                    return String.format(
                            "%s/%s/%s/%s/%s/%s",
                            address.getLatitude(), // 0
                            address.getLongitude(), // 1
                            address.getThoroughfare(), // 2
                            address.getSubThoroughfare(), //3
                            address.getPostalCode(), // 4
                            address.getLocality()); // 5
                } else {
                    return String.format(
                            "%s/%s/%s/%s",
                            address.getLatitude(), // 0
                            address.getLongitude(), // 1
                            address.getPostalCode(), // 2
                            address.getLocality()); // 3
                }
            } else return "No address found";
        }
    
        // Format address string after lookup
        @Override
        protected void onPostExecute (String address) {
    
            String[] addressFields = TextUtils.split(address, "/");
            Log.d("ADDRESS ARRAY", Arrays.toString(addressFields));
    
            // Workaround: doInBackground can only return Strings instead of, for example, an
            // Address instance or a String[] directly. To be able to use TextUtils.isEmpty()
            // on fields returned by this method, set each String that currently reads "null" to
            // a null reference
            for (int fieldcnt = 0; fieldcnt < addressFields.length; ++fieldcnt) {
                if (addressFields[fieldcnt].equals("null"))
                    addressFields[fieldcnt] = null;
            }
    
            switch (addressFields.length) {
                case 4:
                    mStreet = null;
                    mHouseNumber = null;
                    mLatitude = addressFields[0];
                    mLongtitude = addressFields[1];
                    mPostalCode = addressFields[2];
                    mCity = addressFields[3];
                    break;
                case 6:
                    mLatitude = addressFields[0];
                    mLongtitude = addressFields[1];
                    mStreet = addressFields[2];
                    mHouseNumber = addressFields[3];
                    mPostalCode = addressFields[4];
                    mCity = addressFields[5];
                    break;
                default:
                    mLatitude = null;
                    mLongtitude = null;
                    mStreet = null;
                    mHouseNumber = null;
                    mPostalCode = null;
                    mCity = null;
                    break;
            }
    
            Log.d("GeoLocation Street", mStreet);
            Log.d("GeoLocation No.", mHouseNumber);
            Log.d("GeoLocation Postalcode", mPostalCode);
            Log.d("GeoLocation Locality", mCity);
            Log.d("GeoLocation Lat/Lng", "[" + mLatitude + ", " + mLongtitude + 
        "]");
        }
     }
       }
    

    You then instantiate it using

    GeoLocation geoLocation = new GeoLocation(getActivity()); // or (this) if 
    called from an activity and not from a fragment
    mGeoLocation.lookUpAddress(LOCATION_FROM_MAP);
    
    0 讨论(0)
  • 2020-11-22 09:41
    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
    

    For more info of available details, Look at Android-Location-Address

    0 讨论(0)
  • 2020-11-22 09:41

    It seems that no-one has yet provided the solution suggested by Google Docs (https://developer.android.com/training/location/display-address#java). The correct solution should use an IntentService to make the network call for reverse geocoding.

    An intent service is used rather than an AsyncTask as it is not tied to any specific activity. ie. it has its own lifecycle. The IntentService will stop itself when the Geocoding is finished.

    public class GeocodingService extends IntentService {
    
        public GeocodingService() {
            super("GeocodingService");
        }
    
    
        @Override
        protected void onHandleIntent(@Nullable Intent intent) {
            if (intent == null) {
                return;
            }
    
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            String errorMessage = "";
            BCCDatabase BCCDatabase = skicompanion.skicompanion.storage.BCCDatabase.getInstance(getApplicationContext());
    
            // Get the location passed to this service through an extra.
            Location location = intent.getParcelableExtra(
                    "location");
            long trackID = intent.getLongExtra("trackID", -1);
    
            List<Address> addresses = null;
            String addressString = "";
    
            try {
                addresses = geocoder.getFromLocation(
                        location.getLatitude(),
                        location.getLongitude(),
                        1);
            } catch (IOException ioException) {
                // Catch network or other I/O problems.
                errorMessage = "service not available";
                Log.d(Constants.SkiCompanionDebug, errorMessage, ioException);
            } catch (IllegalArgumentException illegalArgumentException) {
                // Catch invalid latitude or longitude values.
                errorMessage = "invalid lat long used";
                Log.d(Constants.SkiCompanionDebug, errorMessage + ". " +
                        "Latitude = " + location.getLatitude() +
                        ", Longitude = " +
                        location.getLongitude(), illegalArgumentException);
            }
    
            // Handle case where no address was found.
            if (addresses == null || addresses.size()  == 0) {
                if (errorMessage.isEmpty()) {
                    errorMessage = "no address found";
                    Log.d(Constants.SkiCompanionDebug, errorMessage);
                }
            } else {
                if(addresses.get(0).getLocality() != null){
                    addressString += addresses.get(0).getLocality() + ", ";
                }
                if(addresses.get(0).getAdminArea() != null){
                    addressString += addresses.get(0).getAdminArea() + ", ";
                }
                if(addresses.get(0).getCountryName() != null){
                    addressString += addresses.get(0).getCountryName();
                }
                //updating DB
                BCCDatabase.setTrackLocation(trackID, addressString);
    
                Log.d(Constants.SkiCompanionDebug, "address found: "+ addressString);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:42

    If you use Kotlin language, I create this method to get the address location directly

    private fun getAddress(latLng: LatLng): String {
    
        val geocoder = Geocoder(this, Locale.getDefault())
        val addresses: List<Address>?
        val address: Address?
        var addressText = ""
    
            addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
    
            if (addresses.isNotEmpty()) {
                address = addresses[0]
                    addressText = address.getAddressLine(0)
            }else{
                addressText = "its not appear"
            }
        return addressText
    }
    

    but this method just return the String value when you call this method

    If you want to get all address you just use this method/function

    fun getAddress(latLng: LatLng){
    
    val geocoder = Geocoder(this, Locale.getDefault())
    val addresses: List<Address>?
    val address: Address?
    var fulladdress = ""
        addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
    
        if (addresses.isNotEmpty()) {
            address = addresses[0]
            fulladdress = address.getAddressLine(0) // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex
            var city = address.getLocality();
            var state = address.getAdminArea();
            var country = address.getCountryName();
            var postalCode = address.getPostalCode();
            var knownName = address.getFeatureName(); // Only if available else return NULL
        }else{
            fulladdress = "Location not found"
        }
    

    }

    0 讨论(0)
  • 2020-11-22 09:46

    Try to use below code using geocoder:

      Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
      List<Address> geoAddresses = geoAddresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
      if (geoAddresses.size() > 0) {
          String mUserLocation = "";
          for (int i = 0; i < 4; i++) { //Since it return only four value we declare this as static.
               mUserLocation = mUserLocation + geoAddresses.get(0).getAddressLine(i).replace(",", "") + ", ";
            } 
        }
    
    0 讨论(0)
  • 2020-11-22 09:47

    1 - You create variables for LocationManager and LocationListener in onCreate method.

    2 - Check if there is a permission so execute the location updates and get lastKnownLocation from locationManager else you ask for permission

    3 - Create onRequestPermissionResult in main class and check if there is a permission then execute the location updates

    4 - Create separated method which includes Geocoder variable and create a list to put the coordinates from your location, so to be safe you check if the List is exist and if each info we want in that list is exist, then you use (getThoroughfare ==> for Street Address), (getLocality ==> for City / State), (getPostalCode ==> for Zip), (getAdminArea ==> for Complete Address)

    5 - Finally you call that method after checking the permission with (lastKnownLocation parameter ==> to show address when the App runs) and in onLocationChanged with (location parameter ==> to show address when location changes)

    Code part:

    LocationManager locationManager;
    
    LocationListener locationListener;
    
    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_main);
    
        locationManager  = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    
        locationListener = new LocationListener() {
    
            @Override
            public void onLocationChanged(Location location) {
    
                updateLocation(location);
    
            }
            @Override public void onStatusChanged(String provider, int status, Bundle extras) {
    
            }
            @Override
            public void onProviderEnabled(String provider) {
            }
            @Override
            public void onProviderDisabled(String provider) {
            }
        };
    
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
    
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    
            Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    
            updateLocation(lastKnownLocation);
    
        }else {
    
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
    
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
    
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        }
    }
    
    
    public void updateLocation ( Location location){
    
    
        Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
        try {
            List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
    
            String address = "Could not find location :(";
    
            if (listAddresses != null && listAddresses.size() > 0) {
    
                if (listAddresses.get(0).getThoroughfare() != null) {
    
                    address = listAddresses.get(0).getThoroughfare() + " ";
                }
    
                if (listAddresses.get(0).getLocality() != null) {
    
                    address += listAddresses.get(0).getLocality() + " ";
                }
    
                if (listAddresses.get(0).getPostalCode() != null) {
    
                    address += listAddresses.get(0).getPostalCode() + " ";
                }
    
                if (listAddresses.get(0).getAdminArea() != null) {
    
                    address += listAddresses.get(0).getAdminArea();
                }
            }
    
            Log.i("Address",address);
    
        } catch (Exception e) {
    
            e.printStackTrace();
    
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题