Java Code Examples for android.location.Address#getLocality()

The following examples show how to use android.location.Address#getLocality() . 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: 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 2
Source File: ReverseGeocoder.java    From medialibrary with Apache License 2.0 6 votes vote down vote up
private String getLocalityAdminForAddress(final Address addr, final boolean approxLocation) {
    if (addr == null)
        return "";
    String localityAdminStr = addr.getLocality();
    if (localityAdminStr != null && !("null".equals(localityAdminStr))) {
        if (approxLocation) {
            // TODO: Uncomment these lines as soon as we may translations
            // for Res.string.around.
            // localityAdminStr =
            // mContext.getResources().getString(Res.string.around) + " " +
            // localityAdminStr;
        }
        String adminArea = addr.getAdminArea();
        if (adminArea != null && adminArea.length() > 0) {
            localityAdminStr += ", " + adminArea;
        }
        return localityAdminStr;
    }
    return null;
}
 
Example 3
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 4
Source File: Utils.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
public static String getCityFromAddress(Address address) {
    if (address == null) {
        return "";
    }
    String geoCity;
    if ((address.getLocality() != null) && !"".equals(address.getLocality())) {
        geoCity = address.getLocality();
    } else {
        geoCity = address.getSubAdminArea();
    }
    if (geoCity == null) {
        geoCity = "";
    }
    return geoCity;
}
 
Example 5
Source File: LocationReader.java    From MuslimMateAndroid with GNU General Public License v3.0 5 votes vote down vote up
public boolean locationToAddress(double latitude, double longitude) {

        Geocoder geocoder = new Geocoder(this.context, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses != null) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                locationInfo.clear();

                String city = returnedAddress.getAdminArea();
                if(city==null) city = returnedAddress.getLocality();

                locationInfo.put("country", returnedAddress.getCountryName());
                locationInfo.put("countrycode", returnedAddress.getCountryCode().toLowerCase());
                locationInfo.put("latitude", ""+returnedAddress.getLatitude());
                locationInfo.put("longitude", ""+returnedAddress.getLongitude());
                if(city!=null)locationInfo.put("city", ""+city);

                String address = "";
                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    address = address + returnedAddress.getAddressLine(i) + "\n";
                }
                locationInfo.put("address", address);

                return true;

            } else {
            }
        } catch (Exception e) {
        }

        return false;
    }
 
Example 6
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 7
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 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;
}
 
Example 8
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 9
Source File: SettingsActivity.java    From your-local-weather with GNU General Public License v3.0 4 votes vote down vote up
private String getDataFromCacheDB() {

            ReverseGeocodingCacheDbHelper mDbHelper = ReverseGeocodingCacheDbHelper.getInstance(getActivity());
            SQLiteDatabase db = mDbHelper.getReadableDatabase();
            long numberOfRowsInAddress = DatabaseUtils.queryNumEntries(db, ReverseGeocodingCacheContract.LocationAddressCache.TABLE_NAME);

            StringBuilder lastRowsFromDB = new StringBuilder();

            lastRowsFromDB.append("There are ");
            lastRowsFromDB.append(numberOfRowsInAddress);
            lastRowsFromDB.append(" of rows in cache.\n\n");

            String[] projection = {
                    ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_ADDRESS,
                    ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_CREATED,
                    ReverseGeocodingCacheContract.LocationAddressCache._ID
            };

            String sortOrder = ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_CREATED + " DESC";

            Cursor cursor = db.query(
                    ReverseGeocodingCacheContract.LocationAddressCache.TABLE_NAME,
                    projection,
                    null,
                    null,
                    null,
                    null,
                    sortOrder
            );

            int rowsCounter = 0;

            while(cursor.moveToNext()) {

                if (!cursor.isFirst()) {
                    lastRowsFromDB.append("\n");
                }

                byte[] cachedAddressBytes = cursor.getBlob(
                        cursor.getColumnIndexOrThrow(ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_ADDRESS));
                Address address = ReverseGeocodingCacheDbHelper.getAddressFromBytes(cachedAddressBytes);

                long recordCreatedinMilis = cursor.getLong(cursor.getColumnIndexOrThrow(ReverseGeocodingCacheContract.LocationAddressCache.COLUMN_NAME_CREATED));
                String recordCreatedTxt = iso8601Format.format(new Date(recordCreatedinMilis));

                int itemId = cursor.getInt(cursor.getColumnIndexOrThrow(ReverseGeocodingCacheContract.LocationAddressCache._ID));

                lastRowsFromDB.append(itemId);
                lastRowsFromDB.append(" : ");
                lastRowsFromDB.append(recordCreatedTxt);
                lastRowsFromDB.append(" : ");
                if (address.getLocality() != null) {
                    lastRowsFromDB.append(address.getLocality());
                    if (!address.getLocality().equals(address.getSubLocality())) {
                        lastRowsFromDB.append(" - ");
                        lastRowsFromDB.append(address.getSubLocality());
                    }
                }

                rowsCounter++;
                if (rowsCounter > 7) {
                    break;
                }
            }
            cursor.close();

            return lastRowsFromDB.toString();
        }
 
Example 10
Source File: VPNFragment.java    From android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void success(final IPService.Data data, Response response) {
    if(mActivity == null) return;

    if(response != null && response.getStatus() == 200) {
        mShowsConnected = data.connected;
        mDetectedCountry = data.country;

        if(!mShowsConnected && mCurrentVPNState.equals(VpnStatus.ConnectionStatus.LEVEL_CONNECTED)) {
            updateIPData();
            return;
        }

        String location = null;
        if (mShowsConnected) {
            mConnectedCard.setVisibility(View.VISIBLE);
        } else {
            mConnectedCard.setVisibility(View.GONE);
            try {
                Geocoder coder = new Geocoder(mActivity);
                List<Address> addressList;
                if (!data.hasCoordinates()) {
                    addressList = coder.getFromLocationName("Country: " + data.country, 1);
                } else {
                    addressList = coder.getFromLocation(data.getLat(), data.getLng(), 1);
                }
                if (addressList != null && addressList.size() > 0) {
                    Address address = addressList.get(0);
                    if (address.getLocality() == null) {
                        location = address.getCountryName();
                    } else {
                        location = String.format("%s, %s", address.getLocality(), address.getCountryCode());
                    }

                    if (address.hasLatitude() && address.hasLongitude())
                        mCurrentLocation = new LatLng(address.getLatitude(), address.getLongitude());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (location == null && data.country != null) {
            Locale locale = new Locale("", data.country);
            location = locale.getDisplayCountry();
        }

        final String finalLocation = location;

        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mIPText.setText(data.ip);
                mLocationText.setText(finalLocation);
            }
        });

        processServers();
        updateMapLocation();
    }
}
 
Example 11
Source File: LocationUtils.java    From DevUtils with Apache License 2.0 2 votes vote down vote up
/**
 * 根据经纬度获取所在地
 * @param latitude  纬度
 * @param longitude 经度
 * @return 所在地
 */
public static String getLocality(final double latitude, final double longitude) {
    Address address = getAddress(latitude, longitude);
    return address == null ? "unknown" : address.getLocality();
}
 
Example 12
Source File: LocationUtils.java    From Android-UtilCode with Apache License 2.0 2 votes vote down vote up
/**
 * 根据经纬度获取所在地
 *
 * @param latitude  纬度
 * @param longitude 经度
 * @return 所在地
 */
public static String getLocality(double latitude, double longitude) {
    Address address = getAddress(latitude, longitude);
    return address == null ? "unknown" : address.getLocality();
}
 
Example 13
Source File: RxLocationTool.java    From RxTools-master with Apache License 2.0 2 votes vote down vote up
/**
 * 根据经纬度获取所在地
 *
 * @param context   上下文
 * @param latitude  纬度
 * @param longitude 经度
 * @return 所在地
 */
public static String getLocality(Context context, double latitude, double longitude) {
    Address address = getAddress(context, latitude, longitude);
    return address == null ? "unknown" : address.getLocality();
}
 
Example 14
Source File: LocationUtils.java    From AndroidUtilCode with Apache License 2.0 2 votes vote down vote up
/**
 * 根据经纬度获取所在地
 *
 * @param latitude  纬度
 * @param longitude 经度
 * @return 所在地
 */
public static String getLocality(double latitude, double longitude) {
    Address address = getAddress(latitude, longitude);
    return address == null ? "unknown" : address.getLocality();
}