android.location.Address Java Examples

The following examples show how to use android.location.Address. 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 Project: PocketMaps   Author: junjunguo   File: GeocodeActivity.java    License: MIT License 6 votes vote down vote up
@Override protected void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  if (!isFavouritesView())
  {
    if (backToListData == null)
    {
      showSearchEngine();
    }
    else
    { // Continue with last search results.
      showAddresses(backToListData, backToListViewOnly);
      backToListData = null;
    }
  }
  else // Favourites-AddressList
  {
    backToListData = null;
    RecyclerView recView = showAddresses(new ArrayList<Address>(), false);
    startFavAsync((MyAddressAdapter)recView.getAdapter());
  }
}
 
Example #2
Source Project: your-local-weather   Author: thuryn   File: Utils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String getCityAndCountryFromAddress(Address address) {
    if (address == null) {
        return "";
    }
    String geoCity = getCityFromAddress(address);
    String geoCountryDistrict = null;
    if(address.getAdminArea() != null) {
        geoCountryDistrict = address.getAdminArea();
    }
    String geoDistrictOfCity = address.getSubLocality();
    String geoCountryName = address.getCountryName();
    if ((geoDistrictOfCity == null) || "".equals(geoDistrictOfCity) || geoCity.equalsIgnoreCase(geoDistrictOfCity)) {
        if ((geoCountryDistrict == null) || "".equals(geoCountryDistrict) || geoCity.equals(geoCountryDistrict)) {
            return formatLocalityToTwoLines((("".equals(geoCity))?"":(geoCity)) + (("".equals(geoCountryName))?"":(", " + geoCountryName)));
        }
        return formatLocalityToTwoLines((("".equals(geoCity))?"":(geoCity + ", ")) + geoCountryDistrict + (("".equals(geoCountryName))?"":(", " + geoCountryName)));
    }
    return formatLocalityToTwoLines((("".equals(geoCity))?"":(geoCity + " - ")) + geoDistrictOfCity + (("".equals(geoCountryName))?"":(", " + geoCountryName)));
}
 
Example #3
Source Project: apigee-android-sdk   Author: apigee   File: EventsActivity.java    License: 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 Project: your-local-weather   Author: thuryn   File: NominatimLocationService.java    License: GNU General Public License v3.0 6 votes vote down vote up
private List<Address> retrieveLocationFromCache(Context context, ReverseGeocodingCacheDbHelper mDbHelper, double latitude, double longitude, String locale) {
    boolean useCache = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Constants.APP_SETTINGS_LOCATION_CACHE_ENABLED, false);

    if (!useCache) {
        return null;
    }

    Address addressFromCache = getResultFromCache(mDbHelper, latitude, longitude, locale);
    appendLog(context, TAG, "address retrieved from cache:", addressFromCache);
    if (addressFromCache == null) {
        return null;
    }
    List<Address> addresses = new ArrayList<>();
    addresses.add(addressFromCache);
    return addresses;
}
 
Example #5
Source Project: SwipeableCard   Author: michelelacorte   File: SwipeableCard.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get street name from latitude and longitude
 * @param lat latitude double
 * @param lon longitude double
 * @param context Context
 * @return String street name
 */
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("SwipeableCard", "Error tryng to retrieve street name from lat long");
    }
    return streetName;
}
 
Example #6
Source Project: open-rmbt   Author: alladin-IT   File: MapLocationRequestTask.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source Project: PocketMaps   Author: junjunguo   File: AddressLoc.java    License: MIT License 6 votes vote down vote up
/** Gets all lines from address.
 *  @return Array with a length of min 1. **/
public static ArrayList<String> getLines(Address address)
{
  ArrayList<String> list = new ArrayList<String>();
  putLine(list, address.getFeatureName());
  putLine(list, address.getThoroughfare());
  putLine(list, address.getUrl());
  putLine(list, address.getPostalCode());
  putLine(list, address.getSubThoroughfare());
  putLine(list, address.getPremises());
  putLine(list, address.getSubAdminArea());
  putLine(list, address.getAdminArea());
  putLine(list, address.getCountryCode());
  putLine(list, address.getCountryName());
  putLine(list, address.getSubLocality());
  putLine(list, address.getLocality());
  putLine(list, address.getPhone());
  for (int i=0; i<=address.getMaxAddressLineIndex(); i++)
  {
    putLine(list, address.getAddressLine(i));
  }
  if (list.size() == 0) { list.add(Variable.getVariable().getCountry()); }
  return list;
}
 
Example #8
Source Project: SamLocationAndGeocoding   Author: kingsammalik   File: LocationAddress.java    License: MIT License 6 votes vote down vote up
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;


}
 
Example #9
Source Project: medialibrary   Author: mayurkaul   File: ReverseGeocoder.java    License: 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 #10
Source Project: EasyWayLocation   Author: prabhat1707   File: EasyWayLocation.java    License: 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 #11
Source Project: EasyWayLocation   Author: prabhat1707   File: GetLocationDetail.java    License: 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 #12
Source Project: SamLocationAndGeocoding   Author: kingsammalik   File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ((Button)findViewById(R.id.check)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                samLocationRequestService = new SamLocationRequestService(MainActivity.this, new SamLocationRequestService.SamLocationListener() {
                    @Override
                    public void onLocationUpdate(Location location, Address address) {
                        Toast.makeText(MainActivity.this,"mapped",Toast.LENGTH_SHORT).show();
                    }
                },REQUEST_CODE);

        }
    });


}
 
Example #13
Source Project: PocketMaps   Author: junjunguo   File: StreetMatcher.java    License: MIT License 6 votes vote down vote up
public static boolean addToList(ArrayList<Address> addressList, String name, double lat, double lon, Locale locale)
{
  for (Address curAddr : addressList)
  {
    if (!curAddr.getAddressLine(GeocoderLocal.ADDR_TYPE_STREET).equals(name)) { continue; }
    double d = GeoMath.fastDistance(lat, lon, curAddr.getLatitude(), curAddr.getLongitude());
    d = d / GeoMath.DEGREE_PER_METER;
    if (d > 1000) { continue; }
    return false;
  }
  Address address = new Address(locale);
  address.setAddressLine(GeocoderLocal.ADDR_TYPE_COUNTRY, Variable.getVariable().getCountry());
  address.setLatitude(lat);
  address.setLongitude(lon);
  address.setAddressLine(GeocoderLocal.ADDR_TYPE_STREET, name);
  addressList.add(address);
  return true;
}
 
Example #14
Source Project: Bus-Tracking-Parent   Author: Rjtsahu   File: LocationHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Nullable
public static String getLocationName(Context context, double lat, double lon) {
    Geocoder g = new Geocoder(context);
    try {
        Address address = g.getFromLocation(lat, lon, 1).get(0);
        String address_line = "";
        int max_address = address.getMaxAddressLineIndex();
        for (int i = 0; i < max_address; i++) {

            address_line += address.getAddressLine(i) + " ";
        }
        return address_line;
    } catch (IOException | IndexOutOfBoundsException e) {
    }
    return null;
}
 
Example #15
Source Project: MuslimMateAndroid   Author: fekracomputers   File: SelectPositionActivity.java    License: 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 #16
Source Project: mollyim-android   Author: mollyim   File: PlacePickerActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Address doInBackground(LatLng... latLngs) {
  if (latLngs.length == 0) return null;
  LatLng latLng = latLngs[0];
  if (latLng == null) return null;
  try {
    List<Address> result = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
    return !result.isEmpty() ? result.get(0) : null;
  } catch (IOException e) {
    Log.w(TAG, "Failed to get address from location", e);
    return null;
  }
}
 
Example #17
Source Project: mollyim-android   Author: mollyim   File: PlacePickerActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onPostExecute(@Nullable Address address) {
  currentAddress = address;
  if (address != null) {
    bottomSheet.showResult(address.getLatitude(), address.getLongitude(), addressToShortString(address), addressToString(address));
  } else {
    bottomSheet.hide();
  }
}
 
Example #18
Source Project: mollyim-android   Author: mollyim   File: PlacePickerActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static @NonNull String addressToShortString(@Nullable Address address) {
  if (address == null) return "";

  String   addressLine = address.getAddressLine(0);
  String[] split       = addressLine.split(",");

  if (split.length >= 3) {
    return split[1].trim() + ", " + split[2].trim();
  } else if (split.length == 2) {
    return split[1].trim();
  } else return split[0].trim();
}
 
Example #19
Source Project: FimiX8-RE   Author: wladimir-computin   File: GglMapLocationManager.java    License: MIT License 5 votes vote down vote up
private void getCity(Location location) {
    List<Address> addList = null;
    try {
        addList = new Geocoder(this.context).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (addList != null && addList.size() > 0) {
        for (int i = 0; i < addList.size(); i++) {
            X8MapGetCityManager.locality = ((Address) addList.get(i)).getLocality();
        }
    }
    this.state = 0;
}
 
Example #20
Source Project: android_9.0.0_r45   Author: lulululbj   File: LocationManagerService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getFromLocationName(String locationName,
        double lowerLeftLatitude, double lowerLeftLongitude,
        double upperRightLatitude, double upperRightLongitude, int maxResults,
        GeocoderParams params, List<Address> addrs) {

    if (mGeocodeProvider != null) {
        return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
                lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
                maxResults, params, addrs);
    }
    return null;
}
 
Example #21
Source Project: SampleApp   Author: saveendhiman   File: LocationHelper.java    License: 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 #22
Source Project: DevUtils   Author: afkT   File: LocationUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据经纬度获取地理位置
 * @param latitude  纬度
 * @param longitude 经度
 * @return {@link Address}
 */
public static Address getAddress(final double latitude, final double longitude) {
    try {
        Geocoder geocoder = new Geocoder(DevUtils.getContext(), Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) return addresses.get(0);
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getAddress");
    }
    return null;
}
 
Example #23
Source Project: your-local-weather   Author: thuryn   File: LogToFile.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void appendLog(Context context, String tag, String text1, double value1, String text2, double value2, String text3, long value3, String text4, Address value4) {
    checkPreferences(context);
    if (!logToFileEnabled || (logFilePathname == null)) {
        return;
    }
    appendLog(context, tag, text1, String.valueOf(value1), text2, String.valueOf(value2), text3, String.valueOf(value3), text4, (value4 != null)? value4.toString() : "null");
}
 
Example #24
Source Project: your-local-weather   Author: thuryn   File: LogToFile.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void appendLog(Context context, String tag, String text1, Address value1) {
    checkPreferences(context);
    if (!logToFileEnabled || (logFilePathname == null)) {
        return;
    }
    appendLog(context, tag, text1, (value1 != null)? value1.toString() : "null");
}
 
Example #25
Source Project: financisto   Author: dsolonenko   File: AddressGeocoder.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static String addressToString(Address address) {
   	StringBuilder sb = new StringBuilder();
   	int max = address.getMaxAddressLineIndex();
   	for (int i = max; i >= 0; i--) {
   		String line = address.getAddressLine(i);
   		if (i < max) {
   			sb.append(", ");        			
   		}
   		sb.append(line);
   	}
   	return sb.toString();
}
 
Example #26
Source Project: your-local-weather   Author: thuryn   File: Utils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String getLocationForVoiceFromAddress(Address address) {
    if (address == null) {
        return "";
    }
    String geoCity = getCityFromAddress(address);
    String geoDistrictOfCity = address.getSubLocality();
    if ((geoDistrictOfCity == null) || "".equals(geoDistrictOfCity) || geoCity.equalsIgnoreCase(geoDistrictOfCity)) {
        return geoCity;
    }
    return (("".equals(geoCity))?"":(geoCity + " ")) + geoDistrictOfCity;
}
 
Example #27
Source Project: PocketMaps   Author: junjunguo   File: MyAddressAdapter.java    License: MIT License 5 votes vote down vote up
/**
 * remove item at the given position
 *
 * @param position
 * @return The removed item.
 */
public Address remove(int position) {
    Address mm = null;
    if (position >= 0 && position < getItemCount()) {
        mm = addressList.remove(position);
        notifyItemRemoved(position);
    }
    return mm;
}
 
Example #28
Source Project: your-local-weather   Author: thuryn   File: Location.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Location(long id,
                int orderId,
                String nickname,
                String localeAbbrev,
                double longitude,
                double latitude,
                float accuracy,
                String locationSource,
                long lastLocationUpdate,
                boolean addressFound,
                boolean enabled,
                Address address) {
    this.id = id;
    this.address = address;
    this.orderId = orderId;
    this.nickname = nickname;
    if (localeAbbrev == null) {
        this.locale = Locale.getDefault();
        this.localeAbbrev = this.locale.getLanguage();
    } else {
        this.localeAbbrev = localeAbbrev;
        this.locale = new Locale(localeAbbrev);
    }
    this.longitude = longitude;
    this.latitude = latitude;
    this.accuracy = accuracy;
    this.locationSource = locationSource;
    this.lastLocationUpdate = lastLocationUpdate;
    this.addressFound = addressFound;
    this.enabled = enabled;
}
 
Example #29
Source Project: your-local-weather   Author: thuryn   File: LocationsDbHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static byte[] getAddressAsBytes(Address address) {
    if (address == null) {
        return null;
    }
    final Parcel parcel = Parcel.obtain();
    address.writeToParcel(parcel, 0);
    byte[] addressBytes = parcel.marshall();
    parcel.recycle();
    return addressBytes;
}
 
Example #30
Source Project: open-quartz   Author: jaredsburrows   File: ChronometerView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update the value of the chronometer.
 */
private void updateText() {
    long millis = SystemClock.elapsedRealtime() - mBaseMillis;
    millis %= TimeUnit.HOURS.toMillis(1);
    millis %= TimeUnit.MINUTES.toMillis(1);
    millis = (millis % TimeUnit.SECONDS.toMillis(1)) / 10;

    location = getLastLocation(getContext());

    if (location != null) {
        text = String.format("Lat:\t %f Long:\t %f\n"
                        + "Alt:\t %f Bearing:\t %f", location.getLatitude(),
                location.getLongitude(), location.getAltitude(),
                location.getBearing());

        if (geocoder != null) {
            try {
                final List<Address> addresses = geocoder
                        .getFromLocation(location.getLatitude(),
                                location.getLongitude(), 10);
                for (Address address : addresses) {
                    text += "\n" + address.getAddressLine(0);
                }
            } catch (Exception ignored) {
            }
        }
    }

    mCentiSecondView.setText(text + " " + millis + " ");

    if (mChangeListener != null) {
        mChangeListener.onChange();
    }
}