Java Code Examples for android.location.Geocoder#getFromLocation()

The following examples show how to use android.location.Geocoder#getFromLocation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SwipeableCardAdapter.java    From SwipeableCard with Apache License 2.0 6 votes vote down vote up
public String getStreetNameFromLatLong(double lat, double lon, Context context)
{
    String streetName = null;
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);

        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder();
            for (int j = 0; j < returnedAddress.getMaxAddressLineIndex(); j++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(j)).append("");
            }
            streetName = strReturnedAddress.toString();
        }
    } catch (IOException e) {
        Log.e("SwipeableCardAdapter", "Error tryng to retrieve street name from lat long");
    }
    return streetName;
}
 
Example 2
Source File: EasyWayLocation.java    From EasyWayLocation with Apache License 2.0 6 votes vote down vote up
public static String getAddress(Context context, Double latitude, Double longitude, boolean country, boolean fullAddress) {
    String add = "";
    Geocoder geoCoder = new Geocoder(((Activity) context).getBaseContext(), Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);

        if (addresses.size() > 0) {
            if (country) {
                add = addresses.get(0).getCountryName();
            } else if (fullAddress) {
                add = addresses.get(0).getFeatureName() + "," + addresses.get(0).getSubLocality() + "," + addresses.get(0).getSubAdminArea() + "," + addresses.get(0).getPostalCode() + "," + addresses.get(0).getCountryName();
            } else {
                add = addresses.get(0).getLocality();
            }
        }


    } catch (IOException e) {
        e.printStackTrace();
    }
    return add.replaceAll(",null", "");
}
 
Example 3
Source File: GetLocationDetail.java    From EasyWayLocation with Apache License 2.0 6 votes vote down vote up
public void getAddress(Double latitude, Double longitude, String key) {
    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
            LocationData locationData = new LocationData();
            locationData.setCity(city);
            locationData.setFull_address(address);
            locationData.setPincode(postalCode);
            locationData.setCountry(country);
            addressCallBack.locationData(locationData);

        }
    } catch (IOException e) {
        e.printStackTrace();
        getAddressFromApi(latitude, longitude, key);
    }
}
 
Example 4
Source File: GetDataTask.java    From Compass with Apache License 2.0 6 votes vote down vote up
@Override
protected LocationData doInBackground(Location... params) {
    Location location = params[0];

    double longitude = location.getLongitude();
    double latitude = location.getLatitude();

    LocationData weatherData = new LocationData();
    weatherData.setLongitude((float) longitude);
    weatherData.setLatitude((float) latitude);
    weatherData.setAltitude(location.getAltitude());

    try {
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            weatherData.setAddressLine(address.getAddressLine(0));
        }
        WeatherManager.getWeatherData(location, weatherData);
    } catch (Exception e) {
        return null;
    }
    return weatherData;
}
 
Example 5
Source File: SplashActivity.java    From protrip with MIT License 6 votes vote down vote up
private void getLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            mCurrentLat = String.valueOf(mLastLocation.getLatitude());
            mCurrentLng = String.valueOf(mLastLocation.getLongitude());
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(mCurrentLat), Double.parseDouble(mCurrentLng), 1);
                //mCurrentLocName = addresses.get(0).getLocality();
                mCurrentLocName = addresses.get(0).getAddressLine(1);

            } catch (Exception e) {
                Log.d(TAG, "Exception");
            }
        }
        skip();
    }

}
 
Example 6
Source File: PLocation.java    From PHONK with GNU General Public License v3.0 6 votes vote down vote up
@PhonkMethod(description = "Get the location name of a given latitude and longitude", example = "")
@PhonkMethodParam(params = {"latitude", "longitude"})
public String getLocationName(double lat, double lon) {
    String gpsLocation = "";
    Geocoder gcd = new Geocoder(getContext(), Locale.getDefault());
    List<Address> addresses;
    try {
        addresses = gcd.getFromLocation(lat, lon, 1);
        gpsLocation = addresses.get(0).getLocality();

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

    return gpsLocation;
}
 
Example 7
Source File: MapLocationUtil.java    From lunzi with Apache License 2.0 6 votes vote down vote up
private Address getAddressByGeoPoint(Location location) {
    Address result = null;
    // 先将Location转换为GeoPoint
    // GeoPoint gp=getGeoByLocation(location);
    try {
        if (location != null) {
            // 获取Geocoder,通过Geocoder就可以拿到地址信息
            Geocoder gc = new Geocoder(mContext, Locale.CHINA);
            List<Address> lstAddress = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (lstAddress.size() > 0) {
                result = lstAddress.get(0);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 8
Source File: EventsActivity.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
public EventContainer(Entity entity) {
    this.eventName = entity.getStringProperty("eventName");
    JsonNode locationObject= (JsonNode) entity.getProperties().get("location");
    if( locationObject != null && Geocoder.isPresent() ) {
        Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
        try {
            List<Address> addressList = myLocation.getFromLocation(locationObject.get("latitude").doubleValue(), locationObject.get("longitude").doubleValue(), 1);
            if( addressList != null && addressList.size() > 0 ) {
                Address locationAddress = addressList.get(0);
                this.eventLocation = locationAddress.getLocality() + ", " + locationAddress.getAdminArea();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 9
Source File: MainActivity.java    From Android-Example with Apache License 2.0 6 votes vote down vote up
public  String getAddress(Context ctx, double latitude, double longitude) {
    StringBuilder result = new StringBuilder();
    try {
        Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);

String locality=address.getLocality();
String city=address.getCountryName();
String region_code=address.getCountryCode();
String zipcode=address.getPostalCode();
double lat =address.getLatitude();
double lon= address.getLongitude();
			
            result.append(locality+" ");
            result.append(city+" "+ region_code+" ");
result.append(zipcode);

        }
    } catch (IOException e) {
        Log.e("tag", e.getMessage());
    }

    return result.toString();
}
 
Example 10
Source File: SelectPositionActivity.java    From MuslimMateAndroid with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(context, 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;
}
 
Example 11
Source File: SelectLocationTabsActivity.java    From MuslimMateAndroid with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(context, 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;
}
 
Example 12
Source File: RxLocationTool.java    From RxTools-master with Apache License 2.0 5 votes vote down vote up
/**
 * 根据经纬度获取地理位置
 *
 * @param context   上下文
 * @param latitude  纬度
 * @param longitude 经度
 * @return {@link Address}
 */
public static Address getAddress(Context context, double latitude, double longitude) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) return addresses.get(0);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 13
Source File: LocationUpdateService.java    From good-weather with GNU General Public License v3.0 5 votes vote down vote up
private void getAndWriteAddressFromGeocoder(String latitude, String longitude, SharedPreferences.Editor editor) {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        String latitudeEn = latitude.replace(",", ".");
        String longitudeEn = longitude.replace(",", ".");
        List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(latitudeEn), Double.parseDouble(longitudeEn), 1);
        if ((addresses != null) && (addresses.size() > 0)) {
            editor.putString(Constants.APP_SETTINGS_GEO_CITY, addresses.get(0).getLocality());
            editor.putString(Constants.APP_SETTINGS_GEO_DISTRICT_OF_CITY, addresses.get(0).getSubLocality());
            editor.putString(Constants.APP_SETTINGS_GEO_COUNTRY_NAME, addresses.get(0).getCountryName());
        }
    } catch (IOException | NumberFormatException ex) {
        Log.e(TAG, "Unable to get address from latitude and longitude", ex);
    }
}
 
Example 14
Source File: InfoUtil.java    From Camera-Roll-Android-App with Apache License 2.0 5 votes vote down vote up
public static Address retrieveAddress(Context context, double lat, double lng) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        if (addresses.size() > 0) {
            return addresses.get(0);
        }
    } catch (IOException | IllegalArgumentException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 15
Source File: LocationHelper.java    From SampleApp with Apache License 2.0 5 votes vote down vote up
/**
 * @param latitude  latitude of address
 * @param longitude longitude of address
 * @return complete address of location
 */

public String getCompleteAddress(double latitude, double longitude) {
    String location = "";
    try {
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            String state, city, zip, street;
            if (address.getAdminArea() != null) {
                state = address.getAdminArea();
            } else {
                state = "";
            }
            if (address.getLocality() != null) {
                city = address.getLocality();
            } else {
                city = "";
            }
            if (address.getPostalCode() != null) {
                zip = address.getPostalCode();
            } else {
                zip = "";
            }

            if (address.getThoroughfare() != null) {
                street = address.getSubLocality() + "," + address.getThoroughfare();
            } else {
                street = address.getSubLocality() + "," + address.getFeatureName();
            }
            location = street + "," + city + "," + zip + "," + state;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return location;
}
 
Example 16
Source File: LocationUtils.java    From Android-UtilCode with Apache License 2.0 5 votes vote down vote up
/**
 * 根据经纬度获取地理位置
 *
 * @param latitude  纬度
 * @param longitude 经度
 * @return {@link Address}
 */
public static Address getAddress(double latitude, double longitude) {
    Geocoder geocoder = new Geocoder(Utils.getContext(), Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) return addresses.get(0);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 17
Source File: LoginUtils.java    From coursera-sustainable-apps with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the postal code at a given latitude / longitude.
 *
 * If you test this method thoroughly, you will see that there are some
 * edge cases it doesn't handle well.
 *
 * @param ctx
 * @param lat
 * @param lng
 * @return
 */
public String getCurrentZipCode(Context ctx, double lat, double lng){
    try {
        Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
        // lat,lng, your current location

        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

        return addresses.get(0).getPostalCode();

    } catch(IOException ex){
        throw new RuntimeException(ex);
    }
}
 
Example 18
Source File: TrackNameUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the reverse geo coding string for a location.
 * 
 * @param context the context
 * @param location the location
 */
private static String getReverseGeoCoding(Context context, Location location) {
  if (location == null || !ApiAdapterFactory.getApiAdapter().isGeoCoderPresent()) {
    return null;
  }
  Geocoder geocoder = new Geocoder(context);
  try {
    List<Address> addresses = geocoder.getFromLocation(
        location.getLatitude(), location.getLongitude(), 1);
    if (addresses.size() > 0) {
      Address address = addresses.get(0);
      int lines = address.getMaxAddressLineIndex();
      if (lines > 0) {
        return address.getAddressLine(0);
      }
      String featureName = address.getFeatureName();
      if (featureName != null) {
        return featureName;
      }
      String thoroughfare = address.getThoroughfare();
      if (thoroughfare != null) {
        return thoroughfare;
      }
      String locality = address.getLocality();
      if (locality != null) {
        return locality;
      }
    }
  } catch (IOException e) {
    // Can safely ignore
  }
  return null;
}
 
Example 19
Source File: LocationBasedCountryDetector.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @return the ISO 3166-1 two letters country code from the location
 */
protected String getCountryFromLocation(Location location) {
    String country = null;
    Geocoder geoCoder = new Geocoder(mContext);
    try {
        List<Address> addresses = geoCoder.getFromLocation(
                location.getLatitude(), location.getLongitude(), 1);
        if (addresses != null && addresses.size() > 0) {
            country = addresses.get(0).getCountryCode();
        }
    } catch (IOException e) {
        Slog.w(TAG, "Exception occurs when getting country from location");
    }
    return country;
}
 
Example 20
Source File: StartRide.java    From kute with Apache License 2.0 4 votes vote down vote up
public void reverseGeocodeSource(final Location location,final Integer index){
    Runnable r=new Runnable() {
        @Override
        public void run() {
            Log.i("ReverseGeocodeFirebase","Started runnable");
            String address="null";
            Geocoder geocoder= new Geocoder(getBaseContext(), Locale.ENGLISH);
            Double latitude=location.getLatitude();
            Double longitude=location.getLongitude();

            try {

                //Place your latitude and longitude
                List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);

                if(addresses != null) {

                    Address fetchedAddress = addresses.get(0);
                    StringBuilder strAddress = new StringBuilder();


                    for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
                        strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
                    }
                    address=strAddress.toString();
                    source_address=address;
                    source_string=fetchedAddress.getAddressLine(1);
                    Log.d("ReverseGeocodeFirebase","The current Address is"+ address);
                    Log.d("ReverseGeocodeFirebase","The current source string  is"+ source_string);
                }

            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
            }
        }

    };
    reverse_geocode_handler.post(r);
}