Java Examples for android.location.Geocoder
The following java examples will help you to understand the usage of android.location.Geocoder. These source code samples are taken from different open source projects.
Example 1
| Project: callerid-for-android-master File: GeocoderHelperProvider.java View source code |
public Geocoder get() { //Only use the built in (aka Android) geocoder if it is present //Otherwise, use the Nominatim geocoder (from OpenStreetMaps) //the GeoCoder.isPresent() method exists only starting with API 9, //so use reflection to check it Class<android.location.Geocoder> geocoderClass = android.location.Geocoder.class; try { Method method = geocoderClass.getMethod("isPresent"); Boolean isPresent = (Boolean) method.invoke(null, (Object[]) null); if (isPresent) { AndroidGeocoder ret = new AndroidGeocoder(application); injector.injectMembers(ret); return ret; } } catch (Exception e) { Ln.d(e, "falling back to Nominatim geocoder"); } return nominatimGeocoder; }
Example 2
| Project: whatstodo-master File: LocationUtils.java View source code |
public static String[] addressFromLocation(Location location) {
List<Address> addresses = null;
Geocoder geocoder = new Geocoder(WhatsToDo.getContext(), Locale.GERMANY);
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);
} catch (IOException e) {
String[] ret = { "Es konnte keine Adresse gefunden werden." };
return ret;
}
String[] addressStrings = new String[addresses.size()];
int i = 0;
for (Address address : addresses) {
addressStrings[i++] = fromAddress(address);
}
return addressStrings;
}Example 3
| Project: AndroidQuickUtils-master File: location.java View source code |
/**
* Gets the location by Coordinates
*
* @param latitude
* @param longitude
* @return Location model
*/
public static LocationModel getLocationByCoordinates(Double latitude, Double longitude) {
try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(QuickUtils.getContext());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
LocationModel locationModel = new LocationModel();
locationModel.latitude = latitude;
locationModel.longitude = longitude;
try {
locationModel.address = addresses.get(0).getAddressLine(0);
} catch (Exception ex) {
QuickUtils.log.e("empty address");
}
try {
locationModel.city = addresses.get(0).getAddressLine(1);
} catch (Exception ex) {
QuickUtils.log.e("empty city");
}
try {
locationModel.country = addresses.get(0).getAddressLine(2);
} catch (Exception ex) {
QuickUtils.log.e("empty country");
}
return locationModel;
} catch (IOException e) {
QuickUtils.log.e("empty location");
return new LocationModel();
}
}Example 4
| Project: Tagsnap-master File: ReverseGeocodingService.java View source code |
@Override
protected Void doInBackground(Location... locations) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = locations[0];
List<Address> addresses = null;
try {
// get all the addresses fro the given latitude, and longitude
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
mAddress = null;
}
// if we have at least one address, use it
if (addresses != null && addresses.size() > 0) {
mAddress = addresses.get(0);
}
return null;
}Example 5
| Project: UBER-For-Real-Estate-master File: GeoFetcher.java View source code |
@Override
protected List<Address> doInBackground(LatLng... latLngs) {
LatLng latLng = latLngs[0];
isExecuting = true;
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
return geocoder.getFromLocation(latLng.latitude, latLng.longitude, 5);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}Example 6
| Project: weiciyuan-master File: GoogleGeoCoderDao.java View source code |
public String get() {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
List<Address> addresses = null;
try {
if (!Utility.isGPSLocationCorrect(geoBean)) {
return null;
}
addresses = geocoder.getFromLocation(geoBean.getLat(), geoBean.getLon(), 1);
} catch (IOException e) {
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
StringBuilder builder = new StringBuilder();
int size = address.getMaxAddressLineIndex();
for (int i = 0; i < size; i++) {
builder.append(address.getAddressLine(i));
}
return builder.toString();
}
return null;
}Example 7
| Project: android-15-master File: LocationBasedCountryDetector.java View source code |
/**
* @return the ISO 3166-1 two letters country code from the location
*/
protected String getCountryFromLocation(Location location) {
String country = null;
Geocoder geoCoder = new Geocoder(mContext);
try {
List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
country = addresses.get(0).getCountryCode();
}
} catch (IOException e) {
Slog.w(TAG, "Exception occurs when getting country from location");
}
return country;
}Example 8
| Project: Android-ReactiveLocation-master File: ReverseGeocodeObservable.java View source code |
@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 (e.getMessage().equalsIgnoreCase("Service not Available")) {
Observable.create(new FallbackReverseGeocodeObservable(locale, latitude, longitude, maxResults)).subscribeOn(Schedulers.io()).subscribe(subscriber);
} else {
subscriber.onError(e);
}
}
}Example 9
| Project: android-sdk-sources-for-api-level-23-master File: GeocoderTest.java View source code |
public void testGeocoder() throws Exception {
Locale locale = new Locale("en", "us");
Geocoder g = new Geocoder(mContext, locale);
List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
assertNotNull(addresses1);
assertEquals(1, addresses1.size());
Address addr = addresses1.get(0);
assertEquals("94305", addr.getFeatureName());
assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
assertEquals("USA", addr.getAddressLine(1));
assertEquals("94305", addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
assertNotNull(addresses2);
assertEquals(1, addresses2.size());
addr = addresses2.get(0);
assertEquals("San Francisco", addr.getFeatureName());
assertEquals("San Francisco, CA", addr.getAddressLine(0));
assertEquals("United States", addr.getAddressLine(1));
assertEquals("San Francisco", addr.getLocality());
assertEquals("CA", addr.getAdminArea());
assertEquals(null, addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}Example 10
| Project: android_explore-master File: LocationOverlay.java View source code |
public String getAddresses() {
String addressString = "ûÓÐÕÒµ½µØÖ·";
Geocoder gc = new Geocoder(mMobileMap, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
sb.append("µØÖ·£º");
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i));
}
addressString = sb.toString();
}
} catch (IOException e) {
}
return addressString;
}Example 11
| Project: android_frameworks_base-master File: GeocoderTest.java View source code |
public void testGeocoder() throws Exception {
Locale locale = new Locale("en", "us");
Geocoder g = new Geocoder(mContext, locale);
List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
assertNotNull(addresses1);
assertEquals(1, addresses1.size());
Address addr = addresses1.get(0);
assertEquals("94305", addr.getFeatureName());
assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
assertEquals("USA", addr.getAddressLine(1));
assertEquals("94305", addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
assertNotNull(addresses2);
assertEquals(1, addresses2.size());
addr = addresses2.get(0);
assertEquals("San Francisco", addr.getFeatureName());
assertEquals("San Francisco, CA", addr.getAddressLine(0));
assertEquals("United States", addr.getAddressLine(1));
assertEquals("San Francisco", addr.getLocality());
assertEquals("CA", addr.getAdminArea());
assertEquals(null, addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}Example 12
| Project: android_packages_apps_Roadrunner-master File: GeoUtils.java View source code |
public static Address getGeoData(Context ctx, Location loc) {
if (!DataNetwork.hasDataConnection(ctx)) {
return null;
}
Geocoder myGeocoder = new Geocoder(ctx);
Address address = null;
try {
List<Address> list = myGeocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (list != null & list.size() > 0) {
address = list.get(0);
}
} catch (Exception e) {
Log.e(TAG, "Failed while retrieving nearest city");
}
return address;
}Example 13
| Project: BetterBatteryStats-master File: GeoUtils.java View source code |
public static Address getGeoData(Context ctx, Location loc) {
if (!DataNetwork.hasDataConnection(ctx)) {
return null;
}
Geocoder myGeocoder = new Geocoder(ctx);
Address address = null;
try {
List<Address> list = myGeocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (list != null & list.size() > 0) {
address = list.get(0);
}
} catch (Exception e) {
Log.e(TAG, "Failed while retrieving nearest city");
}
return address;
}Example 14
| Project: CZD_Android_Lib-master File: LocationUtil.java View source code |
public static String getAddress(Context context, Location loc) {
String result = "";
Geocoder gc = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(loc.getLatitude(), loc.getLongitude(), 10);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
int maxLine = address.getMaxAddressLineIndex();
if (maxLine >= 2) {
result = address.getAddressLine(1) + address.getAddressLine(2);
} else {
result = address.getAddressLine(1);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}Example 15
| Project: flipr-android-master File: GeocodeTask.java View source code |
@Override
protected String doInBackground(Location... params) {
final Geocoder geocoder = new Geocoder(mContext);
final Location location = params[0];
try {
List<Address> addresses;
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0) {
return AddressUtils.addressToName(addresses.get(0));
}
} catch (final IOException e) {
Log.e(TAG, "error looking up location", e);
}
return mContext.getString(R.string.geocoder_lookup_unknown_location);
}Example 16
| Project: frameworks_base_disabled-master File: GeocoderTest.java View source code |
public void testGeocoder() throws Exception {
Locale locale = new Locale("en", "us");
Geocoder g = new Geocoder(mContext, locale);
List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
assertNotNull(addresses1);
assertEquals(1, addresses1.size());
Address addr = addresses1.get(0);
assertEquals("94305", addr.getFeatureName());
assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
assertEquals("USA", addr.getAddressLine(1));
assertEquals("94305", addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
assertNotNull(addresses2);
assertEquals(1, addresses2.size());
addr = addresses2.get(0);
assertEquals("San Francisco", addr.getFeatureName());
assertEquals("San Francisco, CA", addr.getAddressLine(0));
assertEquals("United States", addr.getAddressLine(1));
assertEquals("San Francisco", addr.getLocality());
assertEquals("CA", addr.getAdminArea());
assertEquals(null, addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}Example 17
| Project: lotsofcodingkitty-master File: GeolocationTest.java View source code |
//This part focuses on testing the model Geolocation.
// Create a Geolocation with specific coordinates and
// see if we get the correct city.
public void testGetCityFromLocation() throws IOException {
Context context = getInstrumentation().getTargetContext();
GeoLocation loc = new GeoLocation(53.53, 113.5);
Geocoder gcd = new Geocoder(context, Locale.getDefault());
assertTrue("No service", gcd.isPresent());
Log.d("Geotest", (gcd.getFromLocation(53.33, 113.5, 1)).get(0).getLocality());
String cityName = loc.getCityFromLoc(context);
assertNotNull("No city", cityName);
assertTrue("Wrong City", cityName.equals("Edmonton"));
}Example 18
| Project: mobmonkey-android-master File: MMGeocodeAsyncTask.java View source code |
@Override
protected Object doInBackground(Object... params) {
Geocoder gc = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
Log.d(TAG, TAG + "geocoder present: " + Geocoder.isPresent());
if (Geocoder.isPresent()) {
try {
if (params[0] instanceof String) {
addresses = gc.getFromLocationName((String) params[0], 1);
} else if (params[0] instanceof Double) {
addresses = gc.getFromLocation((Double) params[0], (Double) params[1], 1);
}
} catch (ConnectTimeoutException e) {
e.printStackTrace();
return MMSDKConstants.CONNECTION_TIMED_OUT;
} catch (SocketException e) {
e.printStackTrace();
if (e.getMessage().equals(MMSDKConstants.OPERATION_TIMED_OUT)) {
return MMSDKConstants.CONNECTION_TIMED_OUT;
}
} catch (IOException e) {
e.printStackTrace();
if (e.getMessage().equals(MMSDKConstants.SERVICE_NOT_AVAILABLE)) {
return MMSDKConstants.SERVICE_NOT_AVAILABLE;
}
}
if (addresses != null && addresses.size() == 1) {
return addresses.get(0);
} else {
return null;
}
} else {
return MMSDKConstants.NO_GEOCODER_PRESENT;
}
}Example 19
| Project: MockLocation-master File: AddressLookupTask.java View source code |
@Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double lat = params[0].latitude;
double lng = params[0].longitude;
List<Address> addresses = null;
StringBuilder actualAddress = new StringBuilder();
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null) {
for (Address address : addresses) {
actualAddress.append(String.format("%s, %s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getLocality(), address.getCountryName()) + "\n");
}
}
return actualAddress.toString();
}Example 20
| Project: mqttitude-master File: ReverseGeocodingTask.java View source code |
@Override
protected Void doInBackground(GeocodableLocation... params) {
Log.v(this.toString(), "Doing reverse Geocoder lookup of location");
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
GeocodableLocation l = (GeocodableLocation) params[0];
int r = GEOCODER_NORESULT;
// Return right away if there is already geocoder information available
if (l.getGeocoder() == null) {
try {
List<Address> addresses = geocoder.getFromLocation(l.getLocation().getLatitude(), l.getLocation().getLongitude(), 1);
Log.v(this.toString(), "Geocoder result: " + addresses.get(0).getAddressLine(0));
if (addresses != null && addresses.size() > 0) {
l.setGeocoder(addresses.get(0).getAddressLine(0));
r = GEOCODER_RESULT;
}
} catch (IOException e) {
Log.v(this.toString(), "Geocoder returned no result");
r = GEOCODER_NORESULT;
}
} else {
Log.v(this.toString(), "Geocoder already has result: " + l.getGeocoder());
r = GEOCODER_RESULT;
}
Message.obtain(mHandler, r, l).sendToTarget();
return null;
}Example 21
| Project: onebrick-android-master File: GeoCodeHelper.java View source code |
public static void getGeoCode(@NonNull Context context, @NonNull String address, @NonNull final GeoCoderCallback callback) {
try {
List<Address> geocodeMatches = new Geocoder(context).getFromLocationName(address, 1);
if (!geocodeMatches.isEmpty()) {
double latitude = geocodeMatches.get(0).getLatitude();
double longitude = geocodeMatches.get(0).getLongitude();
Log.d(TAG, "latitude: " + latitude);
Log.d(TAG, "longitude" + longitude);
callback.onResponse(latitude, longitude);
} else {
OneBrickMapRESTClient.getInstance().geocodeResponse(address, new Callback<GeocodeResponse>() {
@Override
public void success(GeocodeResponse geocodeResponse, Response response) {
if (geocodeResponse.isSuccess()) {
Log.d(TAG, "GeoResults: " + geocodeResponse.getLatitude());
Log.d(TAG, "GeoResults: " + geocodeResponse.getLongitude());
callback.onResponse(geocodeResponse.getLatitude(), geocodeResponse.getLongitude());
}
}
@Override
public void failure(RetrofitError error) {
Log.e(TAG, "GeocodeResponse: Failed to parse Geocode Response", error);
}
});
}
} catch (IOException e) {
Log.e("ERROR", "Error to retrieve geocode", e);
}
}Example 22
| Project: panoramio-master File: AddressResolver.java View source code |
@Override
protected String doInBackground(Double... params) {
final double lat = params[0], lng = params[1];
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses.isEmpty())
return null;
Address address = addresses.get(0);
return buildAddressString(address.getAddressLine(0), address.getAddressLine(1), address.getPostalCode(), address.getAdminArea(), address.getLocality(), address.getCountryName());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}Example 23
| Project: Performance-Tweaker-master File: GeoUtils.java View source code |
public static Address getGeoData(Context ctx, Location loc) {
if (!DataNetwork.hasDataConnection(ctx)) {
return null;
}
Geocoder myGeocoder = new Geocoder(ctx);
Address address = null;
try {
List<Address> list = myGeocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (list != null & list.size() > 0) {
address = list.get(0);
}
} catch (Exception e) {
Log.e(TAG, "Failed while retrieving nearest city");
}
return address;
}Example 24
| Project: platform_frameworks_base-master File: GeocoderTest.java View source code |
public void testGeocoder() throws Exception {
Locale locale = new Locale("en", "us");
Geocoder g = new Geocoder(mContext, locale);
List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
assertNotNull(addresses1);
assertEquals(1, addresses1.size());
Address addr = addresses1.get(0);
assertEquals("94305", addr.getFeatureName());
assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
assertEquals("USA", addr.getAddressLine(1));
assertEquals("94305", addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
assertNotNull(addresses2);
assertEquals(1, addresses2.size());
addr = addresses2.get(0);
assertEquals("San Francisco", addr.getFeatureName());
assertEquals("San Francisco, CA", addr.getAddressLine(0));
assertEquals("United States", addr.getAddressLine(1));
assertEquals("San Francisco", addr.getLocality());
assertEquals("CA", addr.getAdminArea());
assertEquals(null, addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}Example 25
| Project: playgrounds-master File: GeoUtil.java View source code |
/**
* Convert the string representation of an address to an
* <code>Address</code>. May return null if null values are provided.
*
* @param context
* @param addr
* the address
* @return
*/
public static Address toAddress(Context context, String addr) {
Geocoder geocoder = null;
Address address = null;
try {
geocoder = new Geocoder(context);
List<Address> addresses = geocoder.getFromLocationName(addr, MAX_ADDRESS_RESULTS);
if (addresses.size() > 0) {
address = addresses.get(0);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return address;
}Example 26
| Project: property-db-master File: GeocoderTest.java View source code |
public void testGeocoder() throws Exception {
Locale locale = new Locale("en", "us");
Geocoder g = new Geocoder(mContext, locale);
List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
assertNotNull(addresses1);
assertEquals(1, addresses1.size());
Address addr = addresses1.get(0);
assertEquals("94305", addr.getFeatureName());
assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
assertEquals("USA", addr.getAddressLine(1));
assertEquals("94305", addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
assertNotNull(addresses2);
assertEquals(1, addresses2.size());
addr = addresses2.get(0);
assertEquals("San Francisco", addr.getFeatureName());
assertEquals("San Francisco, CA", addr.getAddressLine(0));
assertEquals("United States", addr.getAddressLine(1));
assertEquals("San Francisco", addr.getLocality());
assertEquals("CA", addr.getAdminArea());
assertEquals(null, addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}Example 27
| Project: rozkladpkp-android-master File: LocationHelper.java View source code |
@Override
public void onLocationChanged(Location loc) {
Geocoder c = new Geocoder(RozkladPKPApplication.getAppContext());
try {
List<Address> addresses = c.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
location = addresses.get(0).getLocality();
state = LocationState.Ready;
} catch (Exception e) {
}
}Example 28
| Project: tuberun_android-master File: ReverseGeocodeFetcher.java View source code |
private void reverseGeocode(Location l) {
final Geocoder myLocation = new Geocoder(context, Locale.getDefault());
if (myLocation != null) {
task = new AsyncTask<Double, Integer, List<Address>>() {
@Override
protected List<Address> doInBackground(Double... params) {
List<Address> result = new ArrayList<Address>();
try {
result = myLocation.getFromLocation(params[0], params[1], 1);
} catch (Exception e) {
Log.w(getClass().toString(), e);
}
return result;
}
protected void onPostExecute(List<Address> res) {
result = res;
notifyClients();
}
};
task.execute(l.getLatitude(), l.getLongitude());
}
}Example 29
| Project: TweetTopics2.0-master File: GetGeolocationAddressLoader.java View source code |
@Override
public BaseResponse loadInBackground() {
try {
GetGeolocationAddressResponse response = new GetGeolocationAddressResponse();
response.setSingleResult(request.getSingleResult());
Geocoder geocoder = new Geocoder(request.getContext());
List<Address> addresses;
if (request.getSingleResult())
addresses = geocoder.getFromLocationName(request.getText(), 1);
else
addresses = geocoder.getFromLocationName(request.getText(), 5);
ArrayList<Address> address_list = new ArrayList<Address>();
for (Address address : addresses) address_list.add(address);
response.setAddressList(address_list);
return response;
} catch (IOException exception) {
exception.printStackTrace();
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setError(exception, exception.getMessage());
return errorResponse;
}
}Example 30
| Project: VMAT-SGT-Android-master File: GeoCode.java View source code |
public static String getAddress(Context context, GeoPoint p) {
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);
StringBuilder add = new StringBuilder();
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++) add.append(addresses.get(0).getAddressLine(i));
add.append("\n");
}
return add.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 31
| Project: WS171-frameworks-base-master File: GeocoderTest.java View source code |
public void testGeocoder() throws Exception {
Locale locale = new Locale("en", "us");
Geocoder g = new Geocoder(mContext, locale);
List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
assertNotNull(addresses1);
assertEquals(1, addresses1.size());
Address addr = addresses1.get(0);
assertEquals("94305", addr.getFeatureName());
assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
assertEquals("USA", addr.getAddressLine(1));
assertEquals("94305", addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
assertNotNull(addresses2);
assertEquals(1, addresses2.size());
addr = addresses2.get(0);
assertEquals("San Francisco", addr.getFeatureName());
assertEquals("San Francisco, CA", addr.getAddressLine(0));
assertEquals("United States", addr.getAddressLine(1));
assertEquals("San Francisco", addr.getLocality());
assertEquals("CA", addr.getAdminArea());
assertEquals(null, addr.getPostalCode());
assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}Example 32
| Project: AirCastingAndroidClient-master File: AirCastingModule.java View source code |
@Override
protected void configure() {
requestStaticInjection(HttpBuilder.class);
bind(Gson.class).toProvider(GsonProvider.class).in(Scopes.SINGLETON);
bind(HttpClient.class).to(DefaultHttpClient.class);
bind(AirCastingDB.class).toProvider(AirCastingDBProvider.class);
bind(NoteOverlay.class).toProvider(NoteOverlayProvider.class);
bind(Geocoder.class).toProvider(GeocoderProvider.class);
bind(EventBus.class).in(Scopes.SINGLETON);
bindConstant().annotatedWith(SharedPreferencesName.class).to("pl.llp.aircasting_preferences");
bind(BluetoothAdapter.class).toProvider(BluetoothAdapterProvider.class);
bind(TelephonyManager.class).toProvider(new SystemServiceProvider<TelephonyManager>(Context.TELEPHONY_SERVICE));
}Example 33
| Project: android-mvc-framework-master File: GeocodeUtil.java View source code |
// @see http://d.hatena.ne.jp/language_and_engineering/20110828/p1
/**
* 座標ã?‹ã‚‰ä½?所文å—列ã?¸å¤‰æ?›ã€‚ã? ã‚?ã?ªã‚‰ï¼Ÿã‚’è¿”ã?™
*/
public static String point2geostr(double latitude, double longitude, Context context) {
String address_string = new String();
// 変�実行
Geocoder coder = new Geocoder(context, Locale.JAPAN);
try {
List<Address> list_address = coder.getFromLocation(latitude, longitude, 1);
if (!list_address.isEmpty()) {
// 変��功時�,最��変�候補を�得
Address address = list_address.get(0);
address_string = LocationUtil.address2geostr(address);
}
FWUtil.d("地å??:" + address_string);
return address_string;
} catch (IOException e) {
return "?";
}
}Example 34
| Project: android_packages_apps-master File: ReverseGeocoderTask.java View source code |
@Override
protected String doInBackground(Void... params) {
String value = MenuHelper.EMPTY_STRING;
try {
List<Address> address = mGeocoder.getFromLocation(mLat, mLng, 1);
StringBuilder sb = new StringBuilder();
for (Address addr : address) {
int index = addr.getMaxAddressLineIndex();
sb.append(addr.getAddressLine(index));
}
value = sb.toString();
} catch (IOException ex) {
value = MenuHelper.EMPTY_STRING;
Log.e(TAG, "Geocoder exception: ", ex);
} catch (RuntimeException ex) {
value = MenuHelper.EMPTY_STRING;
Log.e(TAG, "Geocoder exception: ", ex);
}
return value;
}Example 35
| Project: android_packages_apps_Gallery-master File: ReverseGeocoderTask.java View source code |
@Override
protected String doInBackground(Void... params) {
String value = MenuHelper.EMPTY_STRING;
try {
List<Address> address = mGeocoder.getFromLocation(mLat, mLng, 1);
StringBuilder sb = new StringBuilder();
for (Address addr : address) {
int index = addr.getMaxAddressLineIndex();
sb.append(addr.getAddressLine(index));
}
value = sb.toString();
} catch (IOException ex) {
value = MenuHelper.EMPTY_STRING;
Log.e(TAG, "Geocoder exception: ", ex);
} catch (RuntimeException ex) {
value = MenuHelper.EMPTY_STRING;
Log.e(TAG, "Geocoder exception: ", ex);
}
return value;
}Example 36
| Project: apigee-android-sdk-master File: CreateEventActivity.java View source code |
@Override
public void onClick(View v) {
String eventNameText = eventNameEditText.getText().toString();
String cityText = cityEditText.getText().toString();
String stateText = stateEditText.getText().toString();
if (eventNameText.isEmpty() || cityText.isEmpty() || stateText.isEmpty()) {
Client.showAlert(CreateEventActivity.this, "Error", "All fields must be filled");
} else {
double latitude = 0.0;
double longitude = 0.0;
if (Geocoder.isPresent()) {
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addressList = geocoder.getFromLocationName(cityText + ", " + stateText, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
latitude = address.getLatitude();
longitude = address.getLongitude();
}
} catch (IOException e) {
}
}
Map<String, Object> eventLocationMap = new HashMap<String, Object>();
eventLocationMap.put("latitude", latitude);
eventLocationMap.put("longitude", longitude);
Map<String, Object> eventEntityMap = new HashMap<String, Object>();
eventEntityMap.put("eventName", eventNameText);
eventEntityMap.put("location", eventLocationMap);
Client.sharedClient().createEvent(publicSwitch.isChecked(), eventEntityMap, new ClientCreateEventCallback() {
@Override
public void onSuccess(Entity createdEntity) {
CreateEventActivity.this.finish();
}
@Override
public void onFailed(String error) {
Client.showAlert(CreateEventActivity.this, "Error Creating Event", error);
}
});
}
}Example 37
| Project: cgeo-master File: GeocoderTest.java View source code |
public static void testAndroidGeocoder() {
final Locale locale = Locale.getDefault();
try {
Locale.setDefault(Locale.US);
// Some emulators don't have access to Google Android geocoder
if (Geocoder.isPresent()) {
final AndroidGeocoder geocoder = new AndroidGeocoder(CgeoApplication.getInstance());
testGeocoder(geocoder.getFromLocationName(TEST_ADDRESS).firstOrError(), "Android", true);
testGeocoder(geocoder.getFromLocation(TEST_COORDS), "Android reverse", true);
} else {
Log.i("not testing absent Android geocoder");
}
} finally {
Locale.setDefault(locale);
}
}Example 38
| Project: FasterGallery-master File: ReverseGeocoderTask.java View source code |
@Override
protected String doInBackground(Void... params) {
String value = MenuHelper.EMPTY_STRING;
try {
List<Address> address = mGeocoder.getFromLocation(mLat, mLng, 1);
StringBuilder sb = new StringBuilder();
for (Address addr : address) {
int index = addr.getMaxAddressLineIndex();
sb.append(addr.getAddressLine(index));
}
value = sb.toString();
} catch (IOException ex) {
value = MenuHelper.EMPTY_STRING;
Log.e(TAG, "Geocoder exception: ", ex);
} catch (RuntimeException ex) {
value = MenuHelper.EMPTY_STRING;
Log.e(TAG, "Geocoder exception: ", ex);
}
return value;
}Example 39
| Project: IBM-Ready-App-for-Telecommunications-master File: HotSpotPresenterImpl.java View source code |
@Override
public Observable<HotSpot> getOfflineHotSpots(String json, Geocoder geocoder, final Location location) {
return Observable.just(json).map(new Func1<String, List<HotSpot>>() {
@Override
public List<HotSpot> call(String s) {
return new Gson().fromJson(s, new TypeToken<List<HotSpot>>() {
}.getType());
}
}).flatMap(new Func1<List<HotSpot>, Observable<HotSpot>>() {
@Override
public Observable<HotSpot> call(List<HotSpot> hotSpots) {
return model.getOfflineHotSpotLocations(location, hotSpots);
}
}).compose(new HotSpotTransformer(geocoder, location)).compose(cacheHotSpots());
}Example 40
| Project: LocationPicker-master File: GPSTracker.java View source code |
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) {
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}Example 41
| Project: MapsMeasure-master File: GeocoderTask.java View source code |
@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 42
| Project: mini-hacks-master File: MainActivity.java View source code |
@Override
public void onConnected(Bundle bundle) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String city = addresses.get(0).getLocality();
cityLabel.setText(city);
Document document = syncManager.getDatabase().getDocument("james");
Map<String, Object> properties = new HashMap<>();
if (document.getProperties() != null) {
properties.putAll(document.getProperties());
}
properties.put("type", "profile");
properties.put("city", city);
try {
document.putProperties(properties);
Log.d(TAG, "Saved document with properties :: %s", document.getProperties().toString());
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
}
}
}Example 43
| Project: MyAndroidApps-master File: EditLocationMapActivity.java View source code |
protected void mapCurrentAddress() {
String addressString = addressText.getText().toString();
Geocoder g = new Geocoder(this);
List<Address> addresses;
try {
addresses = g.getFromLocationName(addressString, 1);
if (addresses.size() > 0) {
address = addresses.get(0);
mMap = mapFragment.getMap();
LatLng latlon = new LatLng(address.getLatitude(), address.getLongitude());
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlon, 15));
mMap.addMarker(new MarkerOptions().position(latlon));
useLocationButton.setEnabled(true);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
}Example 44
| Project: onebusaway-android-master File: GeocoderTask.java View source code |
@Override
protected String doInBackground(Void... voids) {
String address = "";
try {
Geocoder geo = new Geocoder(mContext, Locale.getDefault());
List<Address> addresses = geo.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1);
if (!addresses.isEmpty() && addresses.size() > 0) {
StringBuilder sb = new StringBuilder();
int addressLine = addresses.get(0).getMaxAddressLineIndex();
for (int i = 0; i < addressLine - 1; i++) {
sb.append(addresses.get(0).getAddressLine(i)).append(", ");
}
sb.append(addresses.get(0).getAddressLine(addressLine - 1)).append(".");
address = sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return address;
}Example 45
| Project: open-rmbt-master File: MapLocationSearch.java View source code |
public static void showDialog(final RMBTMapFragment mapFragment) {
if (!Geocoder.isPresent()) {
Toast.makeText(mapFragment.getActivity(), R.string.map_search_location_not_supported, Toast.LENGTH_SHORT).show();
return;
}
final AlertDialog dialog;
final EditText input = new EditText(mapFragment.getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
final AlertDialog.Builder builder = new AlertDialog.Builder(mapFragment.getActivity());
builder.setView(input);
builder.setTitle(R.string.map_search_location_dialog_title);
builder.setMessage(R.string.map_search_location_dialog_info);
builder.setPositiveButton(android.R.string.search_go, new OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
try {
final Runnable taskRunnable = new Runnable() {
@Override
public void run() {
final MapLocationRequestTask task = new MapLocationRequestTask(mapFragment.getActivity(), new OnRequestFinished() {
@Override
public void finished(Address address) {
if (address != null) {
mapFragment.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(address.getLatitude(), address.getLongitude()), mapFragment.getMap().getCameraPosition().zoom));
} else {
Toast.makeText(mapFragment.getActivity(), R.string.map_search_location_dialog_not_found, Toast.LENGTH_SHORT).show();
}
}
});
try {
task.execute(input.getText().toString()).get(TIMEOUT_MS, TimeUnit.NANOSECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
};
final Thread t = new Thread(taskRunnable);
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
dialog = builder.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}Example 46
| Project: oreilly_android-master File: AddLocationMapActivity.java View source code |
protected void mapCurrentAddress() {
String addressString = addressText.getText().toString();
Geocoder g = new Geocoder(this);
List<Address> addresses;
try {
addresses = g.getFromLocationName(addressString, 1);
if (addresses.size() > 0) {
address = addresses.get(0);
List<Overlay> mapOverlays = mapView.getOverlays();
AddressOverlay addressOverlay = new AddressOverlay(address);
mapOverlays.add(myLocationOverlay);
mapOverlays.add(addressOverlay);
mapView.invalidate();
final MapController mapController = mapView.getController();
mapController.animateTo(addressOverlay.getGeopoint(), new Runnable() {
public void run() {
mapController.setZoom(12);
}
});
useLocationButton.setEnabled(true);
} else {
// show the user a note that we failed to get an address
}
} catch (IOException e) {
e.printStackTrace();
}
}Example 47
| Project: platform-android-master File: ReverseGeocodeObservable.java View source code |
@Override
public void call(Subscriber<? super List<Address>> subscriber) {
Geocoder geocoder = new Geocoder(mContext);
List<Address> result = new ArrayList<>();
try {
result = geocoder.getFromLocation(mLatitude, mLongitude, mMaxResults);
} catch (IOException e) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(e);
}
}
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(result);
subscriber.onCompleted();
}
}Example 48
| Project: SVQCOM-master File: GeocoderTask.java View source code |
@Override
protected String doInBackground(Double... location) {
Log.i(getClass().getSimpleName(), String.format("doInBackground %s", Arrays.toString(location)));
Geocoder geoCoder = new Geocoder(context);
try {
List<Address> addresses = geoCoder.getFromLocation(location[0], location[1], 1);
StringBuilder addressString = new StringBuilder();
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getFeatureName() != null) {
addressString.append(address.getFeatureName());
}
if (address.getThoroughfare() != null) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getThoroughfare());
}
if (address.getSubAdminArea() != null) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getSubAdminArea());
}
if (address.getLocality() != null && !address.getLocality().equalsIgnoreCase(address.getSubAdminArea())) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getLocality());
}
if (address.getCountryName() != null) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getCountryName());
}
}
return addressString.toString();
} catch (IOException ioe) {
Log.e(getClass().getSimpleName(), "IOException", ioe);
} catch (IllegalArgumentException ioe) {
Log.e(getClass().getSimpleName(), "IllegalArgumentException", ioe);
}
return null;
}Example 49
| Project: Transit-master File: GeocoderTask.java View source code |
@Override
protected String doInBackground(Void... voids) {
String address = "";
try {
Geocoder geo = new Geocoder(mContext, Locale.getDefault());
List<Address> addresses = geo.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1);
if (!addresses.isEmpty() && addresses.size() > 0) {
StringBuilder sb = new StringBuilder();
int addressLine = addresses.get(0).getMaxAddressLineIndex();
for (int i = 0; i < addressLine - 1; i++) {
sb.append(addresses.get(0).getAddressLine(i)).append(", ");
}
sb.append(addresses.get(0).getAddressLine(addressLine - 1)).append(".");
address = sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return address;
}Example 50
| Project: Ushahidi_Android-master File: GeocoderTask.java View source code |
@Override
protected String doInBackground(Double... location) {
Log.i(getClass().getSimpleName(), String.format("doInBackground %s", Arrays.toString(location)));
Geocoder geoCoder = new Geocoder(context);
try {
List<Address> addresses = geoCoder.getFromLocation(location[0], location[1], 1);
StringBuilder addressString = new StringBuilder();
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getFeatureName() != null) {
addressString.append(address.getFeatureName());
}
if (address.getThoroughfare() != null) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getThoroughfare());
}
if (address.getSubAdminArea() != null) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getSubAdminArea());
}
if (address.getLocality() != null && !address.getLocality().equalsIgnoreCase(address.getSubAdminArea())) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getLocality());
}
if (address.getCountryName() != null) {
if (addressString.length() > 0) {
addressString.append(", ");
}
addressString.append(address.getCountryName());
}
}
return addressString.toString();
} catch (IOException ioe) {
Log.e(getClass().getSimpleName(), "IOException", ioe);
} catch (IllegalArgumentException ioe) {
Log.e(getClass().getSimpleName(), "IllegalArgumentException", ioe);
}
return null;
}Example 51
| Project: WordPress-Android-master File: GeocoderUtils.java View source code |
public static Geocoder getGeocoder(Context context) { // first make sure a Geocoder service exists on this device (requires API 9) if (!Geocoder.isPresent()) { return null; } Geocoder gcd; try { gcd = new Geocoder(context, LanguageUtils.getCurrentDeviceLanguage(context)); } catch (NullPointerException cannotIstantiateEx) { AppLog.e(AppLog.T.UTILS, "Cannot instantiate Geocoder", cannotIstantiateEx); return null; } return gcd; }
Example 52
| Project: WordPress-Networking-Android-master File: GeocoderUtils.java View source code |
public static Geocoder getGeocoder(Context context) { // first make sure a Geocoder service exists on this device (requires API 9) if (!Geocoder.isPresent()) { return null; } Geocoder gcd; try { gcd = new Geocoder(context, Locale.getDefault()); } catch (NullPointerException cannotIstantiateEx) { AppLog.e(AppLog.T.UTILS, "Cannot instantiate Geocoder", cannotIstantiateEx); return null; } return gcd; }
Example 53
| Project: android-playlistr-master File: Utils.java View source code |
public static String getCountryName(Context context, double latitude, double longitude) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Address result;
if (addresses != null && !addresses.isEmpty()) {
return addresses.get(0).getCountryCode();
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
return null;
}Example 54
| Project: android-sensorium-master File: GPSLocationSensor.java View source code |
public void onLocationChanged(Location loc) {
longitude.setValue(loc.getLongitude());
latitude.setValue(loc.getLatitude());
altitude.setValue(loc.getAltitude());
accuracy.setValue(loc.getAccuracy());
bearing.setValue(loc.getBearing());
speed.setValue(loc.getSpeed());
timeMillis = loc.getTime();
Geocoder myLocation = new Geocoder(getContext().getApplicationContext(), Locale.getDefault());
List<Address> list = null;
try {
list = myLocation.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address location = list.get(0);
String addressText = String.format("%s, %s, %s", location.getMaxAddressLineIndex() > 0 ? location.getAddressLine(0) : "", // location.getAdminArea(),
location.getLocality(), location.getCountryName());
address.setValue(addressText);
} else
address.setValue("n/a");
} catch (IOException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
Log.d(SensorRegistry.TAG, sw.toString());
}
notifyListeners();
}Example 55
| Project: ARKOST-master File: Status.java View source code |
private void cekGPS(Location loc) {
TextView tgps = (TextView) findViewById(R.id.lGps);
TextView tlat = (TextView) findViewById(R.id.lLat);
TextView tlon = (TextView) findViewById(R.id.lLon);
TextView ttip = (TextView) findViewById(R.id.lTips);
TextView tjal = (TextView) findViewById(R.id.lLoc);
String alamat = "Alamat tidak diketahui";
// cek posisi
if (loc != null) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
tgps.setText("GPS = Aktif \n");
tlat.setText("Latitude = " + lat + "\n");
tlon.setText("Longitude = " + lon + "\n");
Geocoder gc = new Geocoder(Status.this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(lat, lon, 10);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) sb.append(address.getAddressLine(i)).append(", ");
sb.append(address.getLocality()).append("\n");
} else {
sb.append("Unknown");
}
alamat = sb.toString();
} catch (IOException e) {
}
tjal.setText("Lokasi = " + alamat);
ttip.setText("Tips : Tekan Menu - Refresh untuk meng-update status Anda");
} else {
tgps.setText("GPS = Non Aktif");
tlat.setText("Latitude = Tidak diketahui");
tlon.setText("Longitude = Tidak diketahui");
tjal.setText("Lokasi = Tidak diketahui");
ttip.setText("Tips : Nyalakan GPS. Tekan Menu - setting");
}
// end posisi
}Example 56
| Project: ChineseGithub-master File: LocationUtils.java View source code |
/**
* Get address for location
*
* @param context
* @param location
* @return possibly null address retrieved from location's latitude and
* longitude
*/
public static Address getAddress(final Context context, final Location location) {
if (location == null)
return null;
final Geocoder geocoder = new Geocoder(context);
final List<Address> addresses;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
return null;
}
if (addresses != null && !addresses.isEmpty())
return addresses.get(0);
else
return null;
}Example 57
| Project: gast-lib-master File: GeocodeActivity.java View source code |
public void onLookupLocationClick(View view) {
if (Geocoder.isPresent()) {
EditText addressText = (EditText) findViewById(R.id.enterLocationValue);
try {
List<Address> addressList = new Geocoder(this).getFromLocationName(addressText.getText().toString(), MAX_ADDRESSES);
List<AddressWrapper> addressWrapperList = new ArrayList<AddressWrapper>();
for (Address address : addressList) {
addressWrapperList.add(new AddressWrapper(address));
}
setListAdapter(new ArrayAdapter<AddressWrapper>(this, android.R.layout.simple_list_item_single_choice, addressWrapperList));
} catch (IOException e) {
Log.e(TAG, "Could not geocode address", e);
new AlertDialog.Builder(this).setMessage(R.string.geocodeErrorMessage).setTitle(R.string.geocodeErrorTitle).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
}Example 58
| Project: github-android-master File: LocationUtils.java View source code |
/**
* Get address for location
*
* @param context
* @param location
* @return possibly null address retrieved from location's latitude and
* longitude
*/
public static Address getAddress(final Context context, final Location location) {
if (location == null)
return null;
final Geocoder geocoder = new Geocoder(context);
final List<Address> addresses;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
return null;
}
if (addresses != null && !addresses.isEmpty())
return addresses.get(0);
else
return null;
}Example 59
| Project: GitHubExplorer-master File: LocationUtils.java View source code |
/**
* Get address for location
*
* @param context
* @param location
* @return possibly null address retrieved from location's latitude and
* longitude
*/
public static Address getAddress(final Context context, final Location location) {
if (location == null)
return null;
final Geocoder geocoder = new Geocoder(context);
final List<Address> addresses;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
return null;
}
if (addresses != null && !addresses.isEmpty())
return addresses.get(0);
else
return null;
}Example 60
| Project: kido-android-master File: DeviceInfo.java View source code |
private void getLocationInformation(Context context) {
Location loc = getLastBestLocation(context, 30);
try {
if (loc != null) {
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
isoCountryCode = address.getCountryCode();
countryName = address.getCountryName();
locality = address.getLocality();
adminArea = address.getAdminArea();
subAdminArea = address.getSubAdminArea();
locale = address.getLocale().toString();
}
} else {
Log.e(TAG, "Could not get location information. Did you enabled location services ?");
}
} catch (IOException e) {
e.printStackTrace();
}
}Example 61
| Project: LBS-master File: MapHelper.java View source code |
public static String getAddrByGeoPoint(Context context, Location location) {
StringBuilder sb = new StringBuilder();
try {
Geocoder coder = new Geocoder(context, Locale.CHINA);
List<Address> list = coder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (null != list && 0 != list.size()) {
Address address = list.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i));
}
}
} catch (Exception ex) {
Log.e(Constant.TAG, ex.getMessage());
}
return sb.toString();
}Example 62
| Project: MapsMuzei-master File: MapImage.java View source code |
/**
* Create title and desctiption from the address of the current location
*/
private void createImageTitleAndDescription() {
Geocoder geocoder = new Geocoder(context);
List<Address> addresses = new ArrayList<Address>();
try {
addresses = geocoder.getFromLocation(location.lastLat, location.lastLong, 1);
} catch (IOException e) {
Log.e(TAG, "IO Exception in getFromLocation(). Lat=" + location.lastLat + ", Long=" + location.lastLong, e);
}
if (!addresses.isEmpty()) {
Address address = addresses.get(0);
title = address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "";
description = address.getLocality();
}
}Example 63
| Project: MyTracks-master File: TrackNameUtils.java View source code |
/**
* 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) {
}
return null;
}Example 64
| Project: nearbydemo-master File: NetWorkActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.network);
// »ñÈ¡µ½LocationManager¶ÔÏó
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// ´´½¨Ò»¸öCriteria¶ÔÏó
Criteria criteria = new Criteria();
// ÉèÖôÖÂÔ¾«È·¶È
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// ÉèÖÃÊÇ·ñÐèÒª·µ»Øº£°ÎÐÅÏ¢
criteria.setAltitudeRequired(false);
// ÉèÖÃÊÇ·ñÐèÒª·µ»Ø·½Î»ÐÅÏ¢
criteria.setBearingRequired(false);
// ÉèÖÃÊÇ·ñÔÊÐí¸¶·Ñ·þÎñ
criteria.setCostAllowed(true);
// ÉèÖõçÁ¿ÏûºÄµÈ¼¶
criteria.setPowerRequirement(Criteria.POWER_HIGH);
// ÉèÖÃÊÇ·ñÐèÒª·µ»ØËÙ¶ÈÐÅÏ¢
criteria.setSpeedRequired(false);
// ¸ù¾ÝÉèÖõÄCriteria¶ÔÏ󣬻ñÈ¡×î·ûºÏ´Ë±ê×¼µÄprovider¶ÔÏó
String currentProvider = locationManager.getBestProvider(criteria, true);
Log.d(TAG, "currentProvider: " + currentProvider);
// ¸ù¾Ýµ±Ç°provider¶ÔÏó»ñÈ¡×îºóÒ»´ÎλÖÃÐÅÏ¢
Location currentLocation = locationManager.getLastKnownLocation(currentProvider);
// Èç¹ûλÖÃÐÅϢΪnull£¬ÔòÇëÇó¸üÐÂλÖÃÐÅÏ¢
if (currentLocation == null) {
locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);
}
// ÿ¸ô10Ãë»ñȡһ´ÎλÖÃÐÅÏ¢
while (true) {
currentLocation = locationManager.getLastKnownLocation(currentProvider);
if (currentLocation != null) {
Log.d(TAG, "Latitude: " + currentLocation.getLatitude());
Log.d(TAG, "location: " + currentLocation.getLongitude());
break;
} else {
Log.d(TAG, "Latitude: " + 0);
Log.d(TAG, "location: " + 0);
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
}
}
// ½âÎöµØÖ·²¢ÏÔʾ
Geocoder geoCoder = new Geocoder(this);
try {
int latitude = (int) currentLocation.getLatitude();
int longitude = (int) currentLocation.getLongitude();
List<Address> list = geoCoder.getFromLocation(latitude, longitude, 2);
for (int i = 0; i < list.size(); i++) {
Address address = list.get(i);
Toast.makeText(NetWorkActivity.this, address.getCountryName() + address.getAdminArea() + address.getSubLocality() + address.getFeatureName(), Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
Toast.makeText(NetWorkActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}Example 65
| Project: ProjectTeamRocket-master File: MapsActivity.java View source code |
private void setupMap() {
if (location == null)
return;
setTitle(location);
//Geocoder object to convert a text address into an Address object
findLoc = new Geocoder(this, Locale.US);
LatLng currlocation = null;
//Used to add a marker to the map
MarkerOptions options = new MarkerOptions();
//Converts the location string into a list of possible long/lag addresses
try {
for (int i = 0; i < 10 && (locations == null || locations.size() == 0); i++) {
locations = findLoc.getFromLocationName(location, 1);
}
if (locations.size() >= 1) {
//Object to store lat/long
currlocation = new LatLng(locations.get(0).getLatitude(), locations.get(0).getLongitude());
} else {
new ErrorDialog(R.string.maps_location_find_err).getDialog(this).show();
}
} catch (IOException e) {
new ErrorDialog(R.string.maps_location_inet_err).getDialog(this).show();
}
if (currlocation != null) {
//Sets the markers position
options.position(currlocation);
//Tells the camera where to go
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(currlocation);
//Adds the marker
map.addMarker(options);
//Moves the camera to the CameraUpdate location
map.moveCamera(updatePosition);
}
}Example 66
| Project: QuickSnap-master File: MyLocation.java View source code |
public static String getGeoLocationString(Context context, double latitude, double longitude) {
String addrStr = "";
Geocoder gc = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address addr = addresses.get(0);
for (int i = 0; i < addr.getMaxAddressLineIndex() && i < 1; i++) {
sb.append(addr.getAddressLine(i) + " ");
}
addrStr = sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return addrStr;
}Example 67
| Project: socialize-sdk-android-master File: LocationActivity.java View source code |
public Address geoCode(Location location) throws IOException {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> fromLocation = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (fromLocation != null && fromLocation.size() > 0) {
return fromLocation.get(0);
}
return null;
}Example 68
| Project: soulissapp-master File: ServiceSettingsFragment.java View source code |
private void resetMesg(Preference setHomeLocation) {
String loc = null;
SoulissPreferenceHelper opzioni = SoulissApp.getOpzioni();
if (opzioni.getHomeLatitude() != 0) {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
List<Address> list;
try {
list = geocoder.getFromLocation(opzioni.getHomeLatitude(), opzioni.getHomeLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
loc = address.getLocality();
}
} catch (IOException e) {
Log.e(Constants.TAG, "LOCATION ERR:" + e.getMessage());
}
}
setHomeLocation.setSummary(getString(R.string.opt_homepos_set) + ": " + (loc == null ? "" : loc) + " (" + opzioni.getHomeLatitude() + " : " + opzioni.getHomeLongitude() + ")");
}Example 69
| Project: StreetlightSeattleReporter-master File: MyLocationListener.java View source code |
// http://stackoverflow.com/questions/9409195/how-to-get-complete-address-from-latitude-and-longitude
private String getAddressFromLocation(Location location) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses == null)
return "Could not retrieve the address.";
Address address = addresses.get(0);
String streetAddress = address.getAddressLine(0);
String postalCode = address.getPostalCode();
return streetAddress + ", " + postalCode;
// String streetAddress = addresses.get(0).getAddressLine(0);
// String cityStateZip = addresses.get(0).getAddressLine(1);
// return streetAddress + ", " + cityStateZip;
}Example 70
| Project: ulysses-master File: SearchLocalizedTask.java View source code |
protected Location[] buildLocations() throws IOException {
List<Address> addresses = new Geocoder(context).getFromLocationName(address, 5);
Address address0 = addresses.get(0);
Location[] ls = new Location[1];
ls[0] = new Location("dummy");
ls[0].setLatitude(address0.getLatitude());
ls[0].setLongitude(address0.getLongitude());
return ls;
}Example 71
| Project: uni-master File: Jwf.java View source code |
public static Address getAddress(Context context, double lat, double lng) {
Geocoder geocoder = new Geocoder(context, Locale.KOREA);
try {
List<Address> list = geocoder.getFromLocation(lat, lng, 1);
if (list.size() > 0) {
return list.get(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 72
| Project: wishlist-master File: LocationUtils.java View source code |
/**
* Get address for location
*
* @param context
* @param location
* @return possibly null address retrieved from location's latitude and
* longitude
*/
public static Address getAddress(final Context context, final Location location) {
if (location == null)
return null;
final Geocoder geocoder = new Geocoder(context);
final List<Address> addresses;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
return null;
}
if (addresses != null && !addresses.isEmpty())
return addresses.get(0);
else
return null;
}Example 73
| Project: AndroidLibrary-wada811-master File: GeoUtils.java View source code |
/**
* 緯度経度�ら {@link Address} �リストを�得�る
*
* @param context
* @param latitude 緯度
* @param longitude 軽度
* @param maxResults 1-5, Set 1 when passing less than 1 and set 5 when passing greater than 5
* @return address list
*/
public static List<Address> getAddressList(Context context, double latitude, double longitude, int maxResults) {
if (latitude < -90.0 || latitude > 90.0) {
return new ArrayList<Address>();
}
if (longitude < -180.0 || longitude > 180.0) {
return new ArrayList<Address>();
}
if (maxResults < 1) {
maxResults = 1;
} else if (maxResults > 5) {
maxResults = 5;
}
Geocoder geocoder = new Geocoder(context);
try {
return geocoder.getFromLocation(latitude, longitude, maxResults);
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<Address>();
}
}Example 74
| Project: android_programmering_2014-master File: Worker.java View source code |
public String reverseGeocode(Location location) {
String addressDescription = null;
try {
Geocoder geocoder = new Geocoder(_context);
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);
if (!addressList.isEmpty()) {
Address firstAddress = addressList.get(0);
StringBuilder addressBuilder = new StringBuilder();
for (int i = 0; i <= firstAddress.getMaxAddressLineIndex(); i++) {
if (i != 0)
addressBuilder.append(", ");
addressBuilder.append(firstAddress.getAddressLine(i));
}
addressDescription = addressBuilder.toString();
} else {
addressDescription = reverseGeoCodeWithWebService(location);
}
} catch (IOException ex) {
addressDescription = reverseGeoCodeWithWebService(location);
} catch (Exception ex) {
Log.e("Worker.reverseGeocode", "Error");
}
addDelay();
return addressDescription;
}Example 75
| Project: bearing-master File: ReverseGeocodingTask.java View source code |
/**
* Geocode the query natively and return the result.
*
* Note
* =====
* Some devices, namely Amazon kindles, will report native geocoding support but
* actually not support it. This is caught by a null response. If this occurs
* the fallback {@code addressForRemoteGeocodedQuery} will be called
*
* @param latitude The latitiude of the location to reverse geocode
* @param longitude The longitude of the location to reverse geocode
* @return The geocoded location
*/
private List<Address> addressForNativeGeocodedQuery(Double latitude, Double longitude) {
Geocoder geocoder = new Geocoder(context, locale);
try {
List<Address> results = geocoder.getFromLocation(latitude, longitude, resultCount);
if (results != null && results.size() > 0) {
return results;
}
} catch (IOException ex) {
return addressForRemoteGeocodedQuery(latitude, longitude);
}
return null;
}Example 76
| Project: busradar-master File: AddDialog.java View source code |
public GeoPoint reverseGeocode(String s) {
Geocoder geoCoder = new Geocoder(mcontext, Locale.getDefault());
GeoPoint gp;
try {
List<Address> addresses = geoCoder.getFromLocationName(s + " Madison, WI", 5);
if (addresses.size() > 0) {
gp = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6), (int) (addresses.get(0).getLongitude() * 1E6));
//Toast.makeText(mcontext, gp.getLatitudeE6() / 1E6 + "," + gp.getLongitudeE6() /1E6 , Toast.LENGTH_SHORT).show();
return gp;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 77
| Project: c-geo-master File: cgeoaddresses.java View source code |
@Override
public void run() {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
try {
List<Address> knownLocations = geocoder.getFromLocationName(keyword, 20);
addresses.clear();
for (Address address : knownLocations) {
addresses.add(address);
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoaddresses.loadPlaces.run: " + e.toString());
}
loadPlacesHandler.sendMessage(new Message());
}Example 78
| Project: cgeo-original-master File: addresses.java View source code |
@Override
public void run() {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
try {
List<Address> knownLocations = geocoder.getFromLocationName(keyword, 20);
addresses.clear();
for (Address address : knownLocations) {
addresses.add(address);
}
} catch (Exception e) {
Log.e(Settings.tag, "cgeoaddresses.loadPlaces.run: " + e.toString());
}
loadPlacesHandler.sendMessage(new Message());
}Example 79
| Project: CityBikes-master File: NetworksDBAdapter.java View source code |
public JSONObject getAutomaticNetworkMethod1(GeoPoint center) throws Exception {
this.load();
Geocoder oracle = new Geocoder(mCtx, Locale.ENGLISH);
List<Address> results = oracle.getFromLocation(center.getLatitudeE6() / 1E6, center.getLongitudeE6() / 1E6, 5);
//Log.i("CityBikes",Integer.toString(results.size()));
for (int i = 0; i < results.size(); i++) {
//Log.i("CityBikes",results.get(i).getLocality());
/*for (int j = 0; j < networks.length(); j++){
//Log.i("CityBikes",networks.getJSONObject(j).getString("city_en"));
if (networks.getJSONObject(j).getString("city_en").compareToIgnoreCase(results.get(i).getLocality())==0){
//Log.i("CityBikes","Network found!");
return networks.getJSONObject(j);
}
}*/
}
return null;
}Example 80
| Project: CyclismoProject-master File: TrackNameUtils.java View source code |
/**
* 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) {
}
return null;
}Example 81
| Project: DroidPersianCalendar-master File: GPSLocationDialog.java View source code |
public void showLocation(Location location) {
latitude = String.format(Locale.ENGLISH, "%f", location.getLatitude());
longitude = String.format(Locale.ENGLISH, "%f", location.getLongitude());
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0) {
cityName = addresses.get(0).getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = "";
if (cityName != null) {
result = cityName + "\n\n";
}
// this time, with native digits
result += utils.formatCoordinate(new Coordinate(location.getLatitude(), location.getLongitude()), "\n");
textView.setText(utils.shape(result));
}Example 82
| Project: FineGeotag-master File: ActivitySettings.java View source code |
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
SharedPreferences prefs = getPreferenceScreen().getSharedPreferences();
// Get preferences
Preference pref_check = findPreference(PREF_CHECK);
Preference pref_version = findPreference(PREF_VERSION);
// Set summaries
onSharedPreferenceChanged(prefs, PREF_ENABLED);
onSharedPreferenceChanged(prefs, PREF_TOAST);
onSharedPreferenceChanged(prefs, PREF_ALTITUDE);
onSharedPreferenceChanged(prefs, PREF_ACCURACY);
onSharedPreferenceChanged(prefs, PREF_TIMEOUT);
onSharedPreferenceChanged(prefs, PREF_KNOWN);
// Location settings
Intent locationSettingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if (getPackageManager().queryIntentActivities(locationSettingsIntent, 0).size() > 0)
pref_check.setIntent(locationSettingsIntent);
else
pref_check.setEnabled(false);
// Version
Intent playStoreIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName()));
if (getPackageManager().queryIntentActivities(playStoreIntent, 0).size() > 0)
pref_version.setIntent(playStoreIntent);
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
pref_version.setSummary(pInfo.versionName + "/" + pInfo.versionCode + "\n" + getString(R.string.msg_geocoder) + " " + getString(Geocoder.isPresent() ? R.string.msg_yes : R.string.msg_no));
} catch (PackageManager.NameNotFoundException ignored) {
}
}Example 83
| Project: google-play-services-master File: MainActivity.java View source code |
@Override
public void onConnected(Bundle connectionHint) {
// Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// Determine whether a Geocoder is available.
startIntentService();
}
}Example 84
| Project: hypertrack-live-android-master File: FetchLocationIntentService.java View source code |
@Override
protected void onHandleIntent(Intent intent) {
String errorMessage = "";
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
// Get the location passed to this service through an extra.
String addressToGeocode = intent.getStringExtra(ADDRESS_DATA_EXTRA);
List<Address> addresses = null;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocationName(addressToGeocode, // In this sample, get just a single address.
1);
} catch (IOException ioException) {
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
errorMessage = getString(R.string.invalid_lat_lng_used);
Log.e(TAG, errorMessage, illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(FAILURE_RESULT, new LatLng(0.0, 0.0), receiver);
} else {
Address address = addresses.get(0);
if (address.getLatitude() != 0.0 || address.getLongitude() != 0.0) {
deliverResultToReceiver(SUCCESS_RESULT, new LatLng(address.getLatitude(), address.getLongitude()), receiver);
} else {
deliverResultToReceiver(FAILURE_RESULT, new LatLng(0.0, 0.0), receiver);
}
}
}Example 85
| Project: malcom-lib-android-master File: LocationUtils.java View source code |
public static String getDeviceCityLocation(Context context) {
String res = "";
Location lastKnownLocation = getLocation(context);
//lastKnowLocation could be null, so instead of throw an NPE return an empty String
if (lastKnownLocation == null)
return res;
try {
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude(), 1);
if (addresses.size() > 0) {
res = addresses.get(0).getLocality();
}
} catch (IOException e) {
Log.e(MCMDefines.LOG_TAG, "Error getting city location: " + e.getMessage());
} catch (NullPointerException npe) {
Log.e(MCMDefines.LOG_TAG, "Error getting city location: " + npe.getMessage());
}
return res;
}Example 86
| Project: monkey-island-master File: LoginScreen.java View source code |
public void onClick(View v) {
GPS gps = new GPS(LoginScreen.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
///*
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
String trip = getApplicationContext().getString(R.string.tripfrom) + " " + cityName + " " + getApplicationContext().getString(R.string.tripdest);
Toast.makeText(getApplicationContext(), trip, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
//*/
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}Example 87
| Project: MyBusEdinburgh-master File: GeoSearchLoader.java View source code |
/**
* {@inheritDoc}
*/
@Override
public HashSet<MarkerOptions> loadInBackground() {
final HashSet<MarkerOptions> result = new HashSet<MarkerOptions>();
final Geocoder geo = new Geocoder(getContext());
final List<Address> addressList;
try {
addressList = geo.getFromLocationName(query, MAX_GEO_RESULTS, BOUNDS_SOUTH, BOUNDS_WEST, BOUNDS_NORTH, BOUNDS_EAST);
} catch (IOException e) {
return result;
}
if (addressList != null) {
MarkerOptions mo;
final StringBuilder sb = new StringBuilder();
String locality, postalCode;
for (Address a : addressList) {
mo = new MarkerOptions();
mo.draggable(false);
mo.anchor(0.5f, 1.f);
mo.position(new LatLng(a.getLatitude(), a.getLongitude()));
mo.icon(BitmapDescriptorFactory.defaultMarker());
mo.title(a.getFeatureName());
locality = a.getLocality();
postalCode = a.getPostalCode();
if (locality != null && postalCode != null) {
sb.append(locality).append(',').append(' ').append(postalCode);
mo.snippet(sb.toString());
} else if (locality != null) {
mo.snippet(locality);
} else if (postalCode != null) {
mo.snippet(postalCode);
}
result.add(mo);
sb.setLength(0);
}
}
return result;
}Example 88
| Project: mycitybikes-android-master File: MapLocationItemizedOverlay.java View source code |
private String getFirstReversedGeocodedAddress(GeoPoint position) {
Geocoder geoCoder = new Geocoder(mapView.getContext(), Locale.getDefault());
String address = "";
try {
List<Address> addresses = geoCoder.getFromLocation(position.getLatitudeE6() / 1E6, position.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++) address += addresses.get(0).getAddressLine(i) + "\n";
}
} catch (Exception e) {
Log.e(Constants.TAG, "Unable to reverse geocode address for position " + position + ". " + e.getMessage(), e);
}
return address;
}Example 89
| Project: otm-android-master File: FallbackGeocoder.java View source code |
// *Attempt* to use android's native reverse geocoder
//
// numerous failure conditions can cause this method to return null.
// best used in conjunction with the http geocoder as a fallback.
//
// due to a bug that surfaced in the android geocoder in 9/2014, this method
// was modified to stop using extents to hint/bias the geocoder to favor the
// region containing the instance. See this page for more details:
// http://stackoverflow.com/questions/25621087/android-geocoder-getfromlocationname-stopped-working-with-bounds
public LatLng androidGeocode(String addressText) {
List<Address> addresses;
Geocoder g = new Geocoder(this.context);
try {
addresses = g.getFromLocationName(addressText, 10);
} catch (IOException e) {
Logger.error("Geocoder exception", e);
return null;
}
double instanceRadius, instanceLat, instanceLng;
try {
instanceRadius = currentInstance.getRadius();
instanceLat = currentInstance.getLat();
instanceLng = currentInstance.getLon();
} catch (Exception e) {
Logger.error("Required instance data not found. Exiting android geocoder", e);
return null;
}
// return the first one that is within an acceptable distance
for (Address address : addresses) {
float[] results = new float[1];
Location.distanceBetween(instanceLat, instanceLng, address.getLatitude(), address.getLongitude(), results);
if (results[0] <= instanceRadius) {
return new LatLng(address.getLatitude(), address.getLongitude());
}
}
return null;
}Example 90
| Project: PharmaApp-master File: JSONEmergencyPharmacyScraper.java View source code |
private static void findCoordinates(Pharmacy a) {
try {
Geocoder geocoder = new Geocoder(DataModel.getInstance().getEmergencyPharmaciesContainer().getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocationName(a.getAddress() + " " + a.getTown(), 1);
if (addresses.size() > 0) {
a.setLocation(new Location((float) addresses.get(0).getLatitude(), (float) addresses.get(0).getLongitude()));
}
} catch (IOException ex) {
}
}Example 91
| Project: PinIt-master File: LocationSuggestionProvider.java View source code |
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch(uriMatcher.match(uri)) {
case SEARCH_SUGGEST:
String query = uri.getLastPathSegment();
MatrixCursor cursor = new MatrixCursor(SEARCH_SUGGEST_COLUMNS, 1);
if (Geocoder.isPresent()) {
try {
mGeocoder = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> addressList = mGeocoder.getFromLocationName(query, 5);
for (int i = 0; i < addressList.size(); i++) {
Address address = addressList.get(i);
StringBuilder fullAddress = new StringBuilder();
for (int j = 1; j < address.getMaxAddressLineIndex(); j++) {
fullAddress.append(address.getAddressLine(j));
}
cursor.addRow(new String[] { Integer.toString(i), address.getAddressLine(0).toString(), fullAddress.toString(), address.getLatitude() + "," + address.getLongitude() });
}
return cursor;
} catch (IllegalArgumentException e) {
return getLocationSuggestionsUsingAPI(query, cursor);
} catch (IOException e) {
return getLocationSuggestionsUsingAPI(query, cursor);
}
}
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}Example 92
| Project: private_project_iparty-master File: GPS.java View source code |
/**
* 当gps�纬度�生�化时调用
*/
public void onLocationChanged(Location location) {
/*
* 获��度纬度,�装数�
*/
GPSData data = new GPSData();
data.latitude = location.getLatitude();
data.longitude = location.getLongitude();
Geocoder gc = new Geocoder(mContext, Locale.getDefault());
/*
* 获å?–本地信æ?¯ï¼Œä»Žä¸èŽ·å?–城市å??
* 并�装数�
*/
try {
List<Address> addresses = gc.getFromLocation(data.latitude, data.longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
data.cityName = address.getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}
gpsChangeListener.OnLocationChanged(data);
this.closeGPS();
}Example 93
| Project: ruterandroid-master File: SearchAddressTask.java View source code |
/*
* Do geo mapping.
*/
private void geoMap(String searchAddress) {
final Geocoder geocoder = new Geocoder(activity);
try {
addresses = geocoder.getFromLocationName(searchAddress, 10, 57, 3, 71, 32);
switch(addresses.size()) {
case 0:
Toast.makeText(activity, R.string.failedToFindAddress, Toast.LENGTH_SHORT).show();
handler.onCanceled();
break;
case 1:
foundLocation(addresses.get(0));
break;
default:
showAddressSelection();
break;
}
} catch (IOException e) {
handler.onError(e);
}
}Example 94
| Project: S4-challenge-master File: ToMapActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_map);
mContext = ToMapActivity.this;
Bundle extras = getIntent().getExtras();
if (extras != null) {
locations = extras.getString("locations_str");
}
geocoder = new Geocoder(mContext);
locations_list = new ArrayList<String>(Arrays.asList(locations.split(",")));
if (locations_list != null) {
for (int i = 0; i < locations_list.size(); i++) {
Log.i("getting coordinates", String.valueOf(locations_list.get(i)));
try {
addresses = geocoder.getFromLocationName(String.valueOf(locations_list.get(i)), 1);
if (addresses.size() > 0) {
double latitude = addresses.get(0).getLatitude();
double longitude = addresses.get(0).getLongitude();
MarkerOptions mMarker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(String.valueOf(locations_list.get(i)));
myMarkers_list.add(mMarker);
}
} catch (IOException e) {
Log.e("can't get coordinates", String.valueOf(locations_list.get(i)));
}
}
} else {
Log.e("no locations", "no locations ....");
}
setUpMapIfNeeded();
}Example 95
| Project: smartKill-app-master File: LocationService.java View source code |
@Override
protected Void doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
}
if (addresses != null && addresses.size() > 0) {
// Address address = addresses.get(0);
//TODO dane podaje z geocodera
}
return null;
}Example 96
| Project: stardroid-glass-master File: EditSettingsActivity.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityLightLevelManager = new ActivityLightLevelManager(new ActivityLightLevelChanger(this, null), PreferenceManager.getDefaultSharedPreferences(this));
geocoder = new Geocoder(this);
addPreferencesFromResource(R.xml.preference_screen);
Preference editPreference = findPreference(LOCATION);
// TODO(johntaylor) if the lat long prefs get changed manually, we should really
// reset the placename to "" too.
editPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d(TAG, "Place to be updated to " + newValue);
boolean success = setLatLongFromPlace(newValue.toString());
return success;
}
});
}Example 97
| Project: TeamMeet-master File: IndicationOverlay.java View source code |
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
mLatestTouchGeoPoint = p;
Geocoder geoCoder = new Geocoder(mapView.getContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(mLatestTouchGeoPoint.getLatitudeE6() / 1E6, mLatestTouchGeoPoint.getLongitudeE6() / 1E6, 1);
List<String> addressStringList = new LinkedList<String>();
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++) addressStringList.add(addresses.get(0).getAddressLine(i));
}
// Collections.reverse(addressStringList);
mAddressOfPoint = addressStringList;
} catch (IOException e) {
Log.e(CLASS, "Error using Geocoder: " + e.getLocalizedMessage());
e.printStackTrace();
}
return super.onTap(p, mapView);
}Example 98
| Project: zkBrowser-master File: ResultDetails.java View source code |
protected PointF getLocationFromAddress(String address) {
Geocoder gc = new Geocoder(this);
double latitude = 0.0;
double longitude = 0.0;
address = address + " " + mLocation;
try {
List<Address> foundAdresses = gc.getFromLocationName(address, 5);
latitude = foundAdresses.get(0).getLatitude();
longitude = foundAdresses.get(0).getLongitude();
} catch (Exception e) {
e.printStackTrace();
}
return (new PointF((float) latitude, (float) longitude));
}Example 99
| Project: android-play-location-master File: MainActivity.java View source code |
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
// Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// Determine whether a Geocoder is available.
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_LONG).show();
return;
}
// user has requested an address, since we now have a connection to GoogleApiClient.
if (mAddressRequested) {
startIntentService();
}
}
}Example 100
| Project: 3380-GAS-App-master File: StationRequest.java View source code |
public static LatLng getGeoCoordsFromAddress(Context c, String address) {
Geocoder geocoder = new Geocoder(c);
List<Address> addresses;
try {
addresses = geocoder.getFromLocationName(address, 1);
if (addresses.size() > 0) {
double latitude = addresses.get(0).getLatitude();
double longitude = addresses.get(0).getLongitude();
System.out.println(latitude);
System.out.println(longitude);
return new LatLng(latitude, longitude);
} else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}Example 101
| Project: android-app-study-master File: MyMapViewActivity.java View source code |
private String getMyPosAddress(double dbLat, double dbLon) {
String addressString = "No address found";
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(dbLat, dbLon, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
addressString = address.getAddressLine(0);
addressString = addressString.substring(addressString.indexOf(" ") + 1);
}
} catch (IOException e) {
e.printStackTrace();
}
return addressString;
}