How to get complete address from latitude and longitude?

前端 未结 21 2077
深忆病人
深忆病人 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:24

    Its very easy to get complete address from the Latitude and Longitude using Geocoder class. Following the code sample. Hope this helps!

     if (l != null) {
            val lat = l.latitude
            val lon = l.longitude
    
            val geocoder = Geocoder(this, Locale.getDefault())
            val addresses: List<Address>
    
            addresses = geocoder.getFromLocation(lat, lon, 1) 
    
            val address = addresses[0].getAddressLine(0)
            val address2 = addresses[0].getAddressLine(1)
            val city = addresses[0].locality
            val state = addresses[0].adminArea
            val country = addresses[0].countryName
            val postalCode = addresses[0].postalCode
            val knownName = addresses[0].featureName
    
            val message =
                    "Emergency situation. Call for help. My location is: " + address + "." + "http://maps.google.com/maps?saddr=" + lat + "," + lon
    
        }
    

    You can use only the address value as it gives you all the complete address. If you want individual components, you can use others as well.

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

    You can easily use the following code to get the address.

    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    
    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    
    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    
    public class GPSService extends Service implements LocationListener {
    
    // saving the context for later use
    private final Context mContext;
    
    // if GPS is enabled
    boolean isGPSEnabled = false;
    // if Network is enabled
    boolean isNetworkEnabled = false;
    // if Location co-ordinates are available using GPS or Network
    public boolean isLocationAvailable = false;
    
    // Location and co-ordinates coordinates
    Location mLocation;
    double mLatitude;
    double mLongitude;
    
    // Minimum time fluctuation for next update (in milliseconds)
    private static final long TIME = 30000;
    // Minimum distance fluctuation for next update (in meters)
    private static final long DISTANCE = 20;
    
    // Declaring a Location Manager
    protected LocationManager mLocationManager;
    
    public GPSService(Context context) {
        this.mContext = context;
        mLocationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);
    
    }
    
    /**
     * Returs the Location
     * 
     * @return Location or null if no location is found
     */
    public Location getLocation() {
        try {
    
            // Getting GPS status
            isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
            // If GPS enabled, get latitude/longitude using GPS Services
            if (isGPSEnabled) {
                mLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
                if (mLocationManager != null) {
                    mLocation = mLocationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (mLocation != null) {
                        mLatitude = mLocation.getLatitude();
                        mLongitude = mLocation.getLongitude();
                        isLocationAvailable = true; // setting a flag that
                                                    // location is available
                        return mLocation;
                    }
                }
            }
    
            // If we are reaching this part, it means GPS was not able to fetch
            // any location
            // Getting network status
            isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            if (isNetworkEnabled) {
                mLocationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
                if (mLocationManager != null) {
                    mLocation = mLocationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (mLocation != null) {
                        mLatitude = mLocation.getLatitude();
                        mLongitude = mLocation.getLongitude();
                        isLocationAvailable = true; // setting a flag that
                                                    // location is available
                        return mLocation;
                    }
                }
            }
            // If reaching here means, we were not able to get location neither
            // from GPS not Network,
            if (!isGPSEnabled) {
                // so asking user to open GPS
                askUserToOpenGPS();
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
        // if reaching here means, location was not available, so setting the
        // flag as false
        isLocationAvailable = false;
        return null;
    }
    
    /**
     * Gives you complete address of the location
     * 
     * @return complete address in String
     */
    public String getLocationAddress() {
    
        if (isLocationAvailable) {
    
            Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
            // Get the current location from the input parameter list
            // Create a list to contain the result address
            List<Address> addresses = null;
            try {
                /*
                 * Return 1 address.
                 */
                addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
            } catch (IOException e1) {
                e1.printStackTrace();
                return ("IO Exception trying to get address:" + e1);
            } catch (IllegalArgumentException e2) {
                // Error message to post in the log
                String errorString = "Illegal arguments "
                        + Double.toString(mLatitude) + " , "
                        + Double.toString(mLongitude)
                        + " passed to address service";
                e2.printStackTrace();
                return errorString;
            }
            // If the reverse geocode returned an address
            if (addresses != null && addresses.size() > 0) {
                // Get the first address
                Address address = addresses.get(0);
                /*
                 * Format the first line of address (if available), city, and
                 * country name.
                 */
                String addressText = String.format(
                        "%s, %s, %s",
                        // If there's a street address, add it
                        address.getMaxAddressLineIndex() > 0 ? address
                                .getAddressLine(0) : "",
                        // Locality is usually a city
                        address.getLocality(),
                        // The country of the address
                        address.getCountryName());
                // Return the text
                return addressText;
            } else {
                return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
            }
        } else {
            return "Location Not available";
        }
    
    }
    
    
    
    /**
     * get latitude
     * 
     * @return latitude in double
     */
    public double getLatitude() {
        if (mLocation != null) {
            mLatitude = mLocation.getLatitude();
        }
        return mLatitude;
    }
    
    /**
     * get longitude
     * 
     * @return longitude in double
     */
    public double getLongitude() {
        if (mLocation != null) {
            mLongitude = mLocation.getLongitude();
        }
        return mLongitude;
    }
    
    /**
     * close GPS to save battery
     */
    public void closeGPS() {
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(GPSService.this);
        }
    }
    
    /**
     * show settings to open GPS
     */
    public void askUserToOpenGPS() {
        AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);
    
        // Setting Dialog Title
        mAlertDialog.setTitle("Location not available, Open GPS?")
        .setMessage("Activate GPS to use use location services?")
        .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
                }
            })
            .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    }
                }).show();
    }
    
    /** 
     * Updating the location when location changes
     */
    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
    }
    
    @Override
    public void onProviderDisabled(String provider) {
    }
    
    @Override
    public void onProviderEnabled(String provider) {
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    
    }
    
    0 讨论(0)
  • 2020-11-22 09:29

    Try this My friend

     private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
                String strAdd = "";
                Geocoder geocoder = new Geocoder(this, Locale.getDefault());
                try {
                    List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
                    if (addresses != null) {
                        Address returnedAddress = addresses.get(0);
                        StringBuilder strReturnedAddress = new StringBuilder("");
    
                        for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
                            strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                        }
                        strAdd = strReturnedAddress.toString();
                        Log.w("My Current loction address", strReturnedAddress.toString());
                    } else {
                        Log.w("My Current loction address", "No Address returned!");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.w("My Current loction address", "Canont get Address!");
                }
                return strAdd;
            }
    
    0 讨论(0)
  • 2020-11-22 09:30
      Geocoder geocoder =new Geocoder(mContext, Locale.getDefault());
     // Get the current location from the input parameter list
      Location loc = params[0];
     // Create a list to contain the result address
      List<Address> addresses = null;
      try {
         addresses = geocoder.getFromLocation(loc.getLatitude(),
                 loc.getLongitude(), 10);
     } catch (IOException e1) {
               Log.e("LocationSampleActivity","IO Exception in getFromLocation()");
          e1.printStackTrace();
    
     } catch (IllegalArgumentException e2) {
     // Error message to post in the log
     String errorString = "Illegal arguments " +
             Double.toString(loc.getLatitude()) +
             " , " +
             Double.toString(loc.getLongitude()) +
             " passed to address service";
     Log.e("LocationSampleActivity", errorString);
     e2.printStackTrace();
    
     }
     Address address=null;
     String zip=null;
     String city=null;
     String state=null;
     StringBuffer st=new StringBuffer();
     // If the reverse geocode returned an address
     if (addresses != null && addresses.size() > 0) {
     String       add=addresses.get(0).getAddressLine(0)+","
      +addresses.get(0).getSubAdminArea()+","
      +addresses.get(0).getSubLocality();
      city=addresses.get(0).getLocality();
      state=addresses.get(0).getAdminArea();
         // Get the first address
      for(int i=0 ;i<addresses.size();i++){
      address = addresses.get(i);
       if(address.getPostalCode()!=null){
    zip=address.getPostalCode();
    break;
         }
    
          }
    
    0 讨论(0)
  • 2020-11-22 09:31

    You need to pass the latitude and longitude value.

    Geocoder geocoder;
            List<Address> addresses;
            geocoder = new Geocoder(getContext(), Locale.getDefault());
    
            try {
                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
    
                System.out.println(address+"-------------");
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    0 讨论(0)
  • 2020-11-22 09:31

    Try this code (working)

    public void GetLocation() throws IOException {
    
        LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
    
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
    
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
            }, 200);
    
            return;
        } else {
    
    
    
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Log.d(TAG, "onLocationChanged: " + location.getLongitude() + " , " + location.getLatitude());
    
                }
    
                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {
                    Log.d(TAG, "onStatusChanged: " + s);
    
                }
    
                @Override
                public void onProviderEnabled(String s) {
    
                }
    
                @Override
                public void onProviderDisabled(String s) {
    
                }
            });
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, true);
            Location location = locationManager.getLastKnownLocation(bestProvider);
    
            if (location == null) {
                Toast.makeText(context, "GPS signal not found",
                        Toast.LENGTH_LONG).show();
            }
            if (location != null) {
                Log.e("location", "location--" + location);
                Log.e("latitude at beginning",
                        "@@@@@@@@@@@@@@@" + location.getLatitude());
                // onLocationChanged(location);
            }
    
    
            Geocoder geocoder;
            List<Address> addresses;
            geocoder = new Geocoder(context, Locale.getDefault());
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 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();
    
            Log.d(TAG, "GetLocation: address " + address + " city " + city + " state " + state + " country " + country + " postalCode " + postalCode + " knownName " + knownName);
        }
    }
    
    0 讨论(0)
提交回复
热议问题