Java 类android.location.Address 实例源码
项目:FindX
文件:digiPune.java
/**
* Get list of address by latitude and longitude
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
return addresses;
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
项目:GitHub
文件:GeocodeObservable.java
@Override
public void call(Subscriber<? super List<Address>> subscriber) {
Geocoder geocoder = new Geocoder(ctx);
List<Address> result;
try {
if (bounds != null) {
result = geocoder.getFromLocationName(locationName, maxResults, bounds.southwest.latitude, bounds.southwest.longitude, bounds.northeast.latitude, bounds.northeast.longitude);
} else {
result = geocoder.getFromLocationName(locationName, maxResults);
}
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(result);
subscriber.onCompleted();
}
} catch (IOException e) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(e);
}
}
}
项目:GitHub
文件:ReverseGeocodeObservable.java
@Override
public void call(final Subscriber<? super List<Address>> subscriber) {
Geocoder geocoder = new Geocoder(ctx, locale);
try {
subscriber.onNext(geocoder.getFromLocation(latitude, longitude, maxResults));
subscriber.onCompleted();
} catch (IOException e) {
// If it's a service not available error try a different approach using google web api
if (e.getMessage().equalsIgnoreCase("Service not Available")) {
Observable
.create(new FallbackReverseGeocodeObservable(locale, latitude, longitude, maxResults))
.subscribeOn(Schedulers.io())
.subscribe(subscriber);
} else {
subscriber.onError(e);
}
}
}
项目:android-ponewheel
文件:MainActivity.java
private void startLocationScan() {
RxLocation rxLocation = new RxLocation(this);
LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(TimeUnit.SECONDS.toMillis(5));
rxLocationObserver = rxLocation.location()
.updates(locationRequest)
.subscribeOn(Schedulers.io())
.flatMap(location -> rxLocation.geocoding().fromLocation(location).toObservable())
.observeOn(Schedulers.io())
.subscribeWith(new DisposableObserver<Address>() {
@Override public void onNext(Address address) {
boolean isLocationsEnabled = App.INSTANCE.getSharedPreferences().isLocationsEnabled();
if (isLocationsEnabled) {
mOWDevice.setGpsLocation(address);
} else if (rxLocationObserver != null) {
rxLocationObserver.dispose();
}
}
@Override public void onError(Throwable e) {
Log.e(TAG, "onError: error retreiving location", e);
}
@Override public void onComplete() {
Log.d(TAG, "onComplete: ");
}
});
}
项目:Nibo
文件:LocationAddress.java
public Address getAddressFromLocation(final double latitude, final double longitude,
final Context context) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
address = addressList.get(0);
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
return address;
}
项目:BikeLine
文件:ChooseLocationActivity.java
@Override
public boolean onQueryTextSubmit(String query) {
if(query.length() == 0)
return false;
// get location from api
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
try {
addresses = geocoder.getFromLocationName(query, 1);
} catch (IOException e) {
return true;
}
if(addresses.size() > 0) {
searchPosition = new LatLng(addresses.get(0).getLatitude(), addresses.get(0).getLongitude());
} else {
// no result was found
Toast.makeText(this, getString(R.string.no_result), Toast.LENGTH_SHORT).show();
searchPosition = null;
return true;
}
searchView.clearFocus();
searchHistory.add(query);
updateNowLocation(searchPosition, getString(R.string.choose_location_tag), true);
return true;
}
项目:FindX
文件:GPSTracker.java
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
}
else
{
return null;
}
}
项目:FindX
文件:MyLocation.java
/**
* Try to get Locality
* @return null or locality
*/
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else
{
return null;
}
}
项目:phonk
文件:PLocation.java
@ProtoMethod(description = "Get the location name of a given latitude and longitude", example = "")
@ProtoMethodParam(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;
}
项目:civify-app
文件:GeocoderAdapter.java
@Nullable
@Override
protected Address doInBackground(String... strings) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Address result = null;
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
try {
List<Address> geocodedAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if (geocodedAddresses != null && !geocodedAddresses.isEmpty()) {
result = geocodedAddresses.get(0);
}
} catch (IOException e) {
Throwable cause = e.getCause();
Log.i(TAG, "Error " + (cause != null ? cause.getClass().getSimpleName()
: '(' + e.getClass().getSimpleName() + ": " + e.getMessage() + ')')
+ " getting locality with Geocoder. "
+ "Trying with HTTP/GET on Google Maps API.");
result = geolocateFromGoogleApis(latitude, longitude);
}
return result;
}
项目:civify-app
文件:GeocoderAdapter.java
private Address geolocateFromGoogleApis(double latitude, double longitude) {
String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latitude + ',' + longitude + "&sensor=true&language="
+ Locale.getDefault().getLanguage();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = null;
ResponseBody responseBody = null;
try {
// Synchronous call because we're already on a background thread behind UI
response = client.newCall(request).execute();
responseBody = response.body();
String jsonData = responseBody.string();
if (response.isSuccessful()) return getAddressFromGoogleApis(jsonData);
mErrorMessage = mContext.getString(R.string.unexpected_code)
+ mContext.getString(R.string.on_google) + response.code();
} catch (IOException | JSONException e) {
mErrorMessage = mContext.getString(R.string.error_locality);
mError = e;
} finally {
if (response != null) response.close();
if (responseBody != null) responseBody.close();
}
return null;
}
项目:civify-app
文件:GeocoderAdapter.java
@NonNull
private static String formatAddress(@NonNull Address address) {
String addressText = "";
String streetAndNumber = address.getAddressLine(0);
if (!(streetAndNumber == null || streetAndNumber.isEmpty())) {
addressText += streetAndNumber;
}
String locality = address.getLocality();
if (locality != null) {
if (!(addressText.isEmpty() || addressText.trim().endsWith(","))) {
addressText += ", ";
}
addressText += locality;
}
return addressText;
}
项目:BookED
文件:Authentication.java
public void GetLoc(final String firstname, final String lastname, final String em, final String pass, String loc,String phone, final SharedPreferences sharedPref)
{
Geocoder coder = new Geocoder(Authentication.this);
List<Address> addresses;
try {
addresses = coder.getFromLocationName(loc, 5);
if (addresses == null) {
}
Address location = addresses.get(0);
double lat = location.getLatitude();
double lng = location.getLongitude();
Log.i("Lat",""+lat);
Log.i("Lng",""+lng);
//SetData(firstname,lastname,em,pass,loc,lat,lng,phone,sharedPref);
} catch (IOException e) {
e.printStackTrace();
}
}
项目:wheretomeet-android
文件:FriendsAdapter.java
private String getAddress(double lat, double lng) {
String address=null;
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> list = null;
try{
list = geocoder.getFromLocation(lat, lng, 1);
} catch(Exception e){
e.printStackTrace();
}
if(list == null){
System.out.println("Fail to get address from location");
return null;
}
if(list.size() > 0){
Address addr = list.get(0);
address = removeNULL(addr.getAdminArea())+" "
+ removeNULL(addr.getLocality()) + " "
+ removeNULL(addr.getThoroughfare()) + " "
+ removeNULL(addr.getFeatureName());
}
return address;
}
项目:MuslimMateAndroid
文件:SelectPositionActivity.java
@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;
}
项目:MuslimMateAndroid
文件:SelectLocationTabsActivity.java
@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;
}
项目:FlightSight-client
文件:Utils.java
public static String getLocalityNameEng(Context context, LatLng latLng) {
Geocoder gcd = new Geocoder(context, Locale.US);
try {
List<Address> addresses = gcd.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
String name = address.getCountryName();
if (address.getLocality() != null)
name = address.getLocality();
return name;
}
} catch (IOException ex) {
Log.d(TAG, Log.getStackTraceString(ex));
}
return null;
}
项目:weex-3d-map
文件:DefaultLocation.java
/**
* get address info
*/
private Address getAddress(double latitude, double longitude) {
if(WXEnvironment.isApkDebugable()) {
WXLogUtils.d(TAG, "into--[getAddress] latitude:" + latitude + " longitude:" + longitude);
}
try {
if (mWXSDKInstance == null || mWXSDKInstance.isDestroy()) {
return null;
}
Geocoder gc = new Geocoder(mWXSDKInstance.getContext());
List<Address> list = gc.getFromLocation(latitude, longitude, 1);
if (list != null && list.size() > 0) {
return list.get(0);
}
} catch (Exception e) {
WXLogUtils.e(TAG, e);
}
return null;
}
项目:open-rmbt
文件:MapLocationRequestTask.java
@Override
protected Address doInBackground(String... params) {
final Geocoder geocoder = new Geocoder(activity);
List<Address> addressList;
try {
addressList = geocoder.getFromLocationName(params[0], 1);
if (addressList != null && addressList.size() > 0) {
return addressList.get(0);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
项目:FindX
文件:digiPune.java
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
}
else
{
return null;
}
}
项目:ElephantAsia
文件:AddProfilFragment.java
/**
* Set birth location from map
*
* @param location the location returned from the map picker
*/
public void setBirthLocation(Intent data) {
final Place place = PlacePicker.getPlace(getActivity(), data);
Geocoder geocoder = new Geocoder(getActivity());
try {
List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
elephant.birthLoc.cityName = addresses.get(0).getAddressLine(0);
if (!addresses.get(0).getAddressLine(0).equals(addresses.get(0).getSubAdminArea())) {
elephant.birthLoc.districtName = addresses.get(0).getSubAdminArea();
}
elephant.birthLoc.provinceName = addresses.get(0).getAdminArea();
} catch (IOException e) {
e.printStackTrace();
}
birthLocation.setText(elephant.birthLoc.format());
}
项目:ElephantAsia
文件:EditRegistrationFragment.java
public void setRegistrationLocation(Intent data) {
final Place place = PlacePicker.getPlace(getActivity(), data);
Geocoder geocoder = new Geocoder(getActivity());
try {
List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
elephant.registrationLoc.cityName = addresses.get(0).getAddressLine(0);
if (!addresses.get(0).getAddressLine(0).equals(addresses.get(0).getSubAdminArea())) {
elephant.registrationLoc.districtName = addresses.get(0).getSubAdminArea();
}
elephant.registrationLoc.provinceName = addresses.get(0).getAdminArea();
} catch (IOException e) {
e.printStackTrace();
}
registrationLocation.setText(elephant.registrationLoc.format());
}
项目:ElephantAsia
文件:EditProfilFragment.java
/**
* Set birth location from map
*
* @param location the location returned from the map picker
*/
public void setBirthLocation(Intent data) {
final Place place = PlacePicker.getPlace(getActivity(), data);
Geocoder geocoder = new Geocoder(getActivity());
try {
List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
elephant.birthLoc.cityName = addresses.get(0).getAddressLine(0);
if (!addresses.get(0).getAddressLine(0).equals(addresses.get(0).getSubAdminArea())) {
elephant.birthLoc.districtName = addresses.get(0).getSubAdminArea();
}
elephant.birthLoc.provinceName = addresses.get(0).getAdminArea();
} catch (IOException e) {
e.printStackTrace();
}
birthLocation.setText(elephant.birthLoc.format());
}
项目:iSPY
文件:ShortestDistance.java
private void getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
String address = addresses.get(0).getAddressLine(0);
Log.i("address",address);
String city = addresses.get(0).getLocality();
Log.i("city",city);
String state = addresses.get(0).getAdminArea();
Log.i("state",state);
String country = addresses.get(0).getCountryName();
Log.i("country",country);
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
add=address+", "+city+", "+state+", "+country;
} catch (Exception e) {
e.printStackTrace();
}
}
项目:iSPY
文件:MyLocation.java
private void getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
String address = addresses.get(0).getAddressLine(0);
Log.i("address",address);
String city = addresses.get(0).getLocality();
Log.i("city",city);
String state = addresses.get(0).getAdminArea();
Log.i("state",state);
String country = addresses.get(0).getCountryName();
Log.i("country",country);
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
add=address+", "+city+", "+state+", "+country;
} catch (Exception e) {
e.printStackTrace();
}
}
项目:Android-Wear-Projects
文件:MapsActivity.java
private void updateMemoryPosition(Memory memory, LatLng latLng) {
Geocoder geocoder = new Geocoder(this);
List<Address> matches = null;
try {
matches = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address bestMatch = (matches.isEmpty()) ? null : matches.get(0);
int maxLine = bestMatch.getMaxAddressLineIndex();
memory.city = bestMatch.getAddressLine(maxLine - 1);
memory.country = bestMatch.getAddressLine(maxLine);
memory.latitude = latLng.latitude;
memory.longitude = latLng.longitude;
}
项目:CIA
文件:LocationUtilities.java
/**
* @param activity the activity requesting the location name
* @param location the device's current location
* @return the name of the device's current location if found, or LocationUtilities.NO_LOCATION_NAME otherwise
*/
public static String getLocationName(Activity activity, Location location){
String name = NO_LOCATION_NAME;
if (location != null) {
Geocoder geocoder = new Geocoder(activity);
try {
Address address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1).get(0);
name = address.getThoroughfare();
} catch (IOException e) {
e.printStackTrace();
}
}
return name;
}
项目:GitHub
文件:LocationUtils.java
/**
* 根据经纬度获取地理位置
*
* @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;
}
项目:RLibrary
文件:LocationUtils.java
/**
* 根据经纬度获取地理位置
*
* @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;
}
项目:GitHub
文件:FallbackReverseGeocodeObservable.java
@Override
public void call(Subscriber<? super List<Address>> subscriber) {
try {
subscriber.onNext(alternativeReverseGeocodeQuery());
subscriber.onCompleted();
} catch (Exception ex) {
subscriber.onError(ex);
}
}
项目:coursera-sustainable-apps
文件:LocationHelper.java
public synchronized void getAddress(final AddressConsumer addressConsumer){
locationConsumers.add(new LocationConsumer() {
@Override
public void locationFound(Location location) {
try{
Address addr = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1).get(0);
addressConsumer.addressFound(addr);
}
catch(Exception e){
addressConsumer.addressFound(null);
}
}
});
updateConsumers();
}
项目:coursera-sustainable-apps
文件:LoginUtils.java
/**
* 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);
}
}
项目:coursera-sustainable-apps
文件:GeoUtils.java
public String getCurrentZipCode(double lat, double lng) throws IOException {
List<Address> addressesAtLocation = geocoder.getFromLocation(lat, lng, 1);
String zipCode = (addressesAtLocation.size() > 0) ?
addressesAtLocation.get(0).getPostalCode() :
null;
return zipCode;
}
项目:decoy
文件:NimLocationManager.java
private boolean getLocationAddress(NimLocation location) {
List<Address> list;
boolean ret = false;
try {
list = mGeocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 2);
if (list != null && list.size() > 0) {
Address address = list.get(0);
if (address != null) {
location.setCountryName(address.getCountryName());
location.setCountryCode(address.getCountryCode());
location.setProvinceName(address.getAdminArea());
location.setCityName(address.getLocality());
location.setDistrictName(address.getSubLocality());
location.setStreetName(address.getThoroughfare());
location.setFeatureName(address.getFeatureName());
}
ret = true;
}
} catch (IOException e) {
LogUtil.e(TAG, e + "");
}
int what = ret ? MSG_LOCATION_WITH_ADDRESS_OK : MSG_LOCATION_POINT_OK;
onLocation(location, what);
return ret;
}
项目:AndroidAppBoilerplate
文件:LocationHelper.java
/**
* @param latitude latitude of address
* @param longitude longitude of address
* @return simplified address of location
*/
public String getSimplifiedAddress(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 admin = address.getAdminArea();
String subLocality = address.getSubLocality();
String locality = address.getLocality();
if (admin.length() > 10) {
admin = admin.substring(0, 10) + "..";
}
if (locality != null && subLocality != null) {
location = subLocality + "," + locality;
} else if (subLocality != null) {
location = subLocality + "," + admin;
} else {
location = locality + "," + admin;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return location;
}
项目:decoy
文件:NimGeocoder.java
private static void locationFromGoogleAddress(NimLocation location, Address address) {
location.setStatus(NimLocation.Status.HAS_LOCATION_ADDRESS);
location.setCountryName(address.getCountryName());
location.setCountryCode(address.getCountryCode());
location.setProvinceName(address.getAdminArea());
location.setCityName(address.getLocality());
location.setDistrictName(address.getSubLocality());
location.setStreetName(address.getThoroughfare());
location.setFeatureName(address.getFeatureName());
}
项目:Android-UtilCode
文件:LocationUtils.java
/**
* 根据经纬度获取地理位置
*
* @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;
}
项目:appinventor-extensions
文件:LocationSensor.java
/**
* Provides a textual representation of the current address or
* "No address available".
*/
@SimpleProperty(category = PropertyCategory.BEHAVIOR)
public String CurrentAddress() {
if (hasLocationData &&
latitude <= 90 && latitude >= -90 &&
longitude <= 180 || longitude >= -180) {
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() == 1) {
Address address = addresses.get(0);
if (address != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i));
sb.append("\n");
}
return sb.toString();
}
}
} catch (Exception e) {
// getFromLocation can throw an IOException or an IllegalArgumentException
// a bad result can give an indexOutOfBoundsException
// are there others?
if (e instanceof IllegalArgumentException
|| e instanceof IOException
|| e instanceof IndexOutOfBoundsException ) {
Log.e("LocationSensor", "Exception thrown by getting current address " + e.getMessage());
} else {
// what other exceptions can happen here?
Log.e("LocationSensor",
"Unexpected exception thrown by getting current address " + e.getMessage());
}
}
}
return "No address available";
}
项目:RxJava2-weather-example
文件:Geocoding.java
public Single<List<Address>> fromLocation(final Locale locale, final double latitude, final double longitude, final int maxResults) {
return Single.fromCallable(new Callable<List<Address>>() {
@Override
public List<Address> call() throws Exception {
return getGeocoder(locale).getFromLocation(latitude, longitude, maxResults);
}
});
}
项目:twoh-places-location-api-sample
文件:GeocoderIntentService.java
private void geoCoding(String alamat){
String errorMessage = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(alamat, 1);
} catch (IOException ioException) {
// Menangkap apabila ada I/O atau jaringan error
errorMessage = "Location Service is not available";
ioException.printStackTrace();
Log.e(TAG, errorMessage, ioException);
}
// Apabila tidak ada alamat yang bisa ditemukan
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = "Koordinat tidak ditemukan";
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
} else {
// Mendapatkan hasil dari geocoding alamat, dan ambil lat long nya
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<>();
addressFragments.add(address.getFeatureName());
addressFragments.add(String.valueOf(address.getLatitude()));
addressFragments.add(String.valueOf(address.getLongitude()));
Log.i(TAG, "alamat ditemukan");
deliverResultToReceiver(Constants.SUCCESS_RESULT,
TextUtils.join(System.getProperty("line.separator"), addressFragments));
}
}