android - saber - ¿Cómo obtener una dirección completa de latitud y longitud?
lector de coordenadas (14)
Quiero obtener los siguientes valores de Latitud y Longitud en Android
- Dirección
- Estado de la Ciudad
- Cremallera
- Completa tu direccion
¿Cómo lograr esto?
Está buscando el término Geocodificación.
La historia corta es lo que debes hacer:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Para hacer más debes leer en el Geocoder here .
Intenta usar el siguiente código usando 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(",", "") + ", ";
}
}
Prueba esto Mi amigo
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;
}
Puede usar fácilmente el siguiente código para obtener la dirección.
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;
}
}
Puedes crear clases
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 +
"]");
}
}
}
Luego lo instancias usando
GeoLocation geoLocation = new GeoLocation(getActivity()); // or (this) if
called from an activity and not from a fragment
mGeoLocation.lookUpAddress(LOCATION_FROM_MAP);
Solo usa este método y pasa tu lat, long.
public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {
//Set Address
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
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
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
Utilice GeoCoder para obtener la dirección de Latitud y Longitud.
Compruebe: http://android-er.blogspot.in/2011/02/get-address-from-location-using.html
double latitude = networkLocation.getLatitude();
double longitude = networkLocation.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude , longitude , getApplicationContext(), new GeocoderHandler());
para más información haga clic here
En onCreate () ..
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location == null) {
Toast.makeText(getApplicationContext(), "GPS signal not found",
3000).show();
}
if (location != null) {
Log.e("locatin", "location--" + location);
Log.e("latitude at beginning",
"@@@@@@@@@@@@@@@" + location.getLatitude());
onLocationChanged(location);
}
Escriba el código en onLocationChanged ()
@Override
public void onLocationChanged(Location location) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.e("latitude", "latitude--" + latitude);
try {
Log.e("latitude", "inside latitude--" + latitude);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
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();
locationTxt.setText(address + " " + city + " " + country);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Hay un último truco para obtener la dirección de Lat-Long (Geocoordenadas). Simplemente puede presionar el servicio web google-maps pasando Latitude y longitud. Es simplemente un servicio web GET-Method.
Devolverá la respuesta JSON que se puede analizar fácilmente para obtener la dirección. La URL para esto es:
http://maps.googleapis.com/maps/api/geocode/json?latlng=32,75&sensor=true
Puedes reemplazar 32,75 con latitud y longitud .
La ciudad y el país no siempre entran en la línea 1 y 2 de la dirección ...
El ejemplo está here
Asi que,
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String zip = addresses.get(0).getPostalCode();
String country = addresses.get(0).getCountryName();
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;
}
}
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
Para obtener más información de los detalles disponibles, mira Android-Location-Address
public String getAddress(LatLng latLng) {
String cAddress = "";
if (latLng == null) {
errorMessage = "no_location_data_provided";
Log.wtf(TAG, errorMessage);
return "";
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
// Address found using the Geocoder.
List<Address> addresses = null;
try {
// Using getFromLocation() returns an array of Addresses for the area immediately
// surrounding the given latitude and longitude. The results are a best guess and are
// not guaranteed to be accurate.
addresses = geocoder.getFromLocation(
latLng.latitude,
latLng.longitude,
// In this sample, we get just a single address.
1);
} catch (IOException ioException) {
// Catch network or other I/O problems.
errorMessage = "service_not_available";
Log.e(TAG, errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid_lat_long_used";
Log.e(TAG, errorMessage + ". " +
"Latitude = " + latLng.latitude +
", Longitude = " + latLng.longitude, illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = "no_address_found";
Log.e(TAG, errorMessage);
}
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using {@code getAddressLine},
// join them, and send them to the thread. The {@link android.location.address}
// class provides other options for fetching address details that you may prefer
// to use. Here are some examples:
// getLocality() ("Mountain View", for example)
// getAdminArea() ("CA", for example)
// getPostalCode() ("94043", for example)
// getCountryCode() ("US", for example)
// getCountryName() ("United States", for example)
String allAddress = "";
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
allAddress += address.getAddressLine(i) + " ";
}
if (address.getAdminArea() != null) {
state = address.getAdminArea();
} else {
state = "";
}
if (address.getLocality() != null) {
city = address.getLocality();
} else {
city = "";
}
if (address.getPostalCode() != null) {
postalCode = address.getPostalCode();
} else {
postalCode = "";
}
Log.i(TAG, "address_found");
//driverAddress = TextUtils.join(System.getProperty("line.separator"), addressFragments);
cAddress = allAddress;
Log.e("result", cAddress.toString());
}
return cAddress;
}