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 File: NominatimLocationService.java    From your-local-weather with 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 #2
Source File: MainActivity.java    From SamLocationAndGeocoding with 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 #3
Source File: LocationHelper.java    From Bus-Tracking-Parent with 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 #4
Source File: StreetMatcher.java    From PocketMaps with 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 #5
Source File: GeocodeActivity.java    From PocketMaps with 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 #6
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 #7
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 #8
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 #9
Source File: LocationAddress.java    From SamLocationAndGeocoding with 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 #10
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 #11
Source File: AddressLoc.java    From PocketMaps with 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 #12
Source File: Utils.java    From your-local-weather with 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 #13
Source File: MapLocationRequestTask.java    From open-rmbt with 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 #14
Source File: SwipeableCard.java    From SwipeableCard with 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 #15
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 #16
Source File: AddressGeocoder.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
public String resolveAddressFromLocation(double latitude, double longitude) {
       try {
       	lastException = null;
           List<Address> results = geocoder.getFromLocation(latitude, longitude, 1);
           if (results.size() > 0) {
           	Address address = results.get(0);
           	return addressToString(address);
           }
       } catch (IOException e) {
       	lastException = e;
           Log.e("Geocoder", "Problem using geocoder", e);            
       }		
       return null;
}
 
Example #17
Source File: BackendFuser.java    From android_packages_apps_UnifiedNlp with Apache License 2.0 5 votes vote down vote up
public List<Address> getFromLocation(double latitude, double longitude, int maxResults,
                                     String locale) {
    if (backendHelpers.isEmpty())
        return null;
    ArrayList<Address> result = new ArrayList<Address>();
    for (BackendHelper backendHelper : backendHelpers) {
        List<Address> backendResult = backendHelper
                .getFromLocation(latitude, longitude, maxResults, locale);
        if (backendResult != null) {
            result.addAll(backendResult);
        }
    }
    return result;
}
 
Example #18
Source File: LocationService.java    From FineGeotag with GNU General Public License v3.0 5 votes vote down vote up
private static List<String> reverseGeocode(Location location, Context context) {
    List<String> listLine = new ArrayList<>();
    if (location != null && Geocoder.isPresent())
        try {
            Geocoder geocoder = new Geocoder(context);
            List<Address> listPlace = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (listPlace != null && listPlace.size() > 0) {
                for (int l = 0; l < listPlace.get(0).getMaxAddressLineIndex(); l++)
                    listLine.add(listPlace.get(0).getAddressLine(l));
            }
        } catch (IOException ignored) {
        }
    return listLine;
}
 
Example #19
Source File: ReverseGeocodingTask.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
@Override
    protected Void doInBackground(Void... voids) {
        GeocoderNominatim nominatim = new GeocoderNominatim(ApplicationConstants.USER_AGENT);
        try {
            List<Address> addresses = nominatim.getFromLocation(latitude, longitude, 1);//only get one location
            if (addresses != null && addresses.size() > 0) {
                reverseGeocodedAddress = addresses.get(0);
                Bundle bundle = addresses.get(0).getExtras();
                String osm_type = bundle.getString("osm_type");
                AppLog.log(addresses.get(0));
                //only osm nodes are filtered though
//                if (osm_type.equals("node")) {
                double nodeLat = reverseGeocodedAddress.getLatitude();
                double nodeLon = reverseGeocodedAddress.getLongitude();
                //The geocoding is considered as valid if the node location
                //is under the distance 4 meters form the provided location (user click location on map)
                AppLog.log(distance(latitude, nodeLat, longitude, nodeLon, 0, 0));
                if (distance(latitude, nodeLat, longitude, nodeLon, 0, 0) < 4) {
                    long osm_id = bundle.getLong("osm_id");
                    getNode(connection, osm_id);
                }
//                } else {
//                    //Do noting
//                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
Example #20
Source File: LocationActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
private void reverseGeocode(Location location) {
  double latitude = location.getLatitude();
  double longitude = location.getLongitude();
  List<Address> addresses = null;
  Geocoder gc = new Geocoder(this, Locale.getDefault());
  try {
    addresses = gc.getFromLocation(latitude, longitude, 10);
  } catch (IOException e) {
    Log.e(TAG, "Geocoder I/O Exception", e);
  }
}
 
Example #21
Source File: BackendHelper.java    From android_packages_apps_UnifiedNlp with Apache License 2.0 5 votes vote down vote up
public List<Address> getFromLocation(double latitude, double longitude, int maxResults,
                                     String locale) {
    try {
        return backend.getFromLocation(latitude, longitude, maxResults, locale);
    } catch (Exception e) {
        Log.w(TAG, e);
        unbind();
        return null;
    }
}
 
Example #22
Source File: MapUtils.java    From live-app-android with MIT License 5 votes vote down vote up
public static Single<String> getAddress(Context context, final LatLng latLng) {
    final Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    return Single.fromCallable(new Callable<String>() {
        @Override
        public String call() {
            try {
                List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
                if (!addresses.isEmpty()) {
                    String formattedAddress = "";
                    Address address = addresses.get(0);
                    if (address.getSubThoroughfare() != null) {
                        formattedAddress += address.getSubThoroughfare();
                    }
                    if (address.getThoroughfare() != null) {
                        if (!formattedAddress.isEmpty()) {
                            formattedAddress += " ";
                        }
                        formattedAddress += address.getThoroughfare();
                    }
                    if (address.getLocality() != null) {
                        if (!formattedAddress.isEmpty()) {
                            formattedAddress += ", ";
                        }
                        formattedAddress += address.getLocality();
                    }
                    return formattedAddress;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example #23
Source File: MozillaLocationService.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
protected void reportNewLocation(Location location, Address address) {
    if (locationUpdateService != null) {
        locationUpdateService.onLocationChanged(
                location,
                address);
    } else {
        locationUpdateServiceActions.add(
                new LocationAndAddressToUpdate(
                        location,
                        address));
        bindLocationUpdateService();
    }
}
 
Example #24
Source File: LocationUpdateService.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void processAddresses(Location location, List<Address> addresses) {
    appendLog(getBaseContext(), TAG, "processUpdateOfLocation:addresses:", addresses);
    Address resolvedAddress = null;
    if ((addresses != null) && (addresses.size() > 0)) {
        resolvedAddress = addresses.get(0);
    }
    appendLog(getBaseContext(), TAG, "processUpdateOfLocation:location:", location, ", address=", resolvedAddress);
    onLocationChanged(location, resolvedAddress);
}
 
Example #25
Source File: NominatimLocationService.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
private byte[] getAddressAsBytes(Address address) {
    final Parcel parcel = Parcel.obtain();
    address.writeToParcel(parcel, 0);
    byte[] addressBytes = parcel.marshall();
    parcel.recycle();
    return addressBytes;
}
 
Example #26
Source File: Venue.java    From mConference-Framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Address getAddressFromLocation (Context context, String locationAddress) {
    Address address = null;
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        address = geocoder.getFromLocationName(locationAddress, 1).get(0);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return address;
}
 
Example #27
Source File: PlacePickerActivity.java    From mollyim-android with 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 #28
Source File: AndroidGeocoder.java    From callerid-for-android with GNU General Public License v3.0 5 votes vote down vote up
public List<Address> getFromLocation(double latitude, double longitude,
		int maxResults) throws IOException {
	try{
		return geocoder.getFromLocation(latitude, longitude, maxResults);
	}catch(IOException e){
		//probably service not available - fall back to the backup geocoder
		return nominatimGeocoder.getFromLocation(latitude, longitude, maxResults);
	}
}
 
Example #29
Source File: GeocoderTask.java    From MapsMeasure with Apache License 2.0 5 votes vote down vote up
@Override
protected Address doInBackground(final String... locationName) {
    // Creating an instance of Geocoder class
    Geocoder geocoder = new Geocoder(map.getBaseContext());
    try {
        // Get only the best result that matches the input text
        List<Address> addresses = geocoder.getFromLocationName(locationName[0], 1);
        return addresses != null && !addresses.isEmpty() ? addresses.get(0) : null;
    } catch (IOException e) {
        if (BuildConfig.DEBUG) Logger.log(e);
        e.printStackTrace();
        return null;
    }
}
 
Example #30
Source File: GeocodeProviderV1.java    From android_packages_apps_UnifiedNlp with Apache License 2.0 5 votes vote down vote up
@Override
public String onGetFromLocationName(String locationName, double lowerLeftLatitude,
                                    double lowerLeftLongitude, double upperRightLatitude,
                                    double upperRightLongitude, int maxResults,
                                    GeocoderParams params, List<Address> addresses) {
    List<Address> fuserResult = backendFuser.getFromLocationName(locationName, maxResults,
            lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
            params.getLocale().toString());
    return handleResult(addresses, fuserResult);
}