android.location.Geocoder Java Examples

The following examples show how to use android.location.Geocoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: incubator-weex-playground   Author: apache   File: DefaultLocation.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get address info
 */
private Address getAddress(double latitude, double longitude) {
  WXLogUtils.d(TAG, "into--[getAddress] latitude:" + latitude + " longitude:" + longitude);
  try {
    if (mContext == null) {
      return null;
    }
    Geocoder gc = new Geocoder(mContext);
    List<Address> list = gc.getFromLocation(latitude, longitude, 1);
    if (list != null && list.size() > 0) {
      return list.get(0);
    }
  } catch (Exception e) {
    WXLogUtils.e(TAG, e);
  }
  return null;
}
 
Example #2
Source Project: your-local-weather   Author: thuryn   File: Utils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void getAndWriteAddressFromGeocoder(Geocoder geocoder,
                                                  Address address,
                                                  double latitude,
                                                  double longitude,
                                                  boolean resolveAddressByOS,
                                                  Context context) {
    try {
        final LocationsDbHelper locationDbHelper = LocationsDbHelper.getInstance(context);
        if (resolveAddressByOS) {
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if((addresses != null) && (addresses.size() > 0)) {
                address = addresses.get(0);
            }
        }
        if(address != null) {
            locationDbHelper.updateAutoLocationAddress(context, PreferenceUtil.getLanguage(context), address);
        } else {
            locationDbHelper.setNoLocationFound();
        }
    } catch (IOException | NumberFormatException ex) {
        Log.e(Utils.class.getName(), "Unable to get address from latitude and longitude", ex);
    }
}
 
Example #3
Source Project: EasyWayLocation   Author: prabhat1707   File: EasyWayLocation.java    License: Apache License 2.0 6 votes vote down vote up
public static String getAddress(Context context, Double latitude, Double longitude, boolean country, boolean fullAddress) {
    String add = "";
    Geocoder geoCoder = new Geocoder(((Activity) context).getBaseContext(), Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);

        if (addresses.size() > 0) {
            if (country) {
                add = addresses.get(0).getCountryName();
            } else if (fullAddress) {
                add = addresses.get(0).getFeatureName() + "," + addresses.get(0).getSubLocality() + "," + addresses.get(0).getSubAdminArea() + "," + addresses.get(0).getPostalCode() + "," + addresses.get(0).getCountryName();
            } else {
                add = addresses.get(0).getLocality();
            }
        }


    } catch (IOException e) {
        e.printStackTrace();
    }
    return add.replaceAll(",null", "");
}
 
Example #4
Source Project: EasyWayLocation   Author: prabhat1707   File: GetLocationDetail.java    License: Apache License 2.0 6 votes vote down vote up
public void getAddress(Double latitude, Double longitude, String key) {
    try {
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses != null && addresses.size() > 0) {

            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String country = addresses.get(0).getCountryName();
            String postalCode = addresses.get(0).getPostalCode();
            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
            LocationData locationData = new LocationData();
            locationData.setCity(city);
            locationData.setFull_address(address);
            locationData.setPincode(postalCode);
            locationData.setCountry(country);
            addressCallBack.locationData(locationData);

        }
    } catch (IOException e) {
        e.printStackTrace();
        getAddressFromApi(latitude, longitude, key);
    }
}
 
Example #5
Source Project: ridesharing-android   Author: hypertrack   File: MapUtils.java    License: MIT License 6 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()) {
                    Address address = addresses.get(0);
                    return address.getSubThoroughfare() + " " + address.getThoroughfare() + ", " + address.getLocality();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example #6
Source Project: Bus-Tracking-Parent   Author: Rjtsahu   File: LocationHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Nullable
public static String getLocationName(Context context, double lat, double lon) {
    Geocoder g = new Geocoder(context);
    try {
        Address address = g.getFromLocation(lat, lon, 1).get(0);
        String address_line = "";
        int max_address = address.getMaxAddressLineIndex();
        for (int i = 0; i < max_address; i++) {

            address_line += address.getAddressLine(i) + " ";
        }
        return address_line;
    } catch (IOException | IndexOutOfBoundsException e) {
    }
    return null;
}
 
Example #7
Source Project: Android-Example   Author: velmurugan35   File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
public  String getAddress(Context ctx, double latitude, double longitude) {
    StringBuilder result = new StringBuilder();
    try {
        Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);

String locality=address.getLocality();
String city=address.getCountryName();
String region_code=address.getCountryCode();
String zipcode=address.getPostalCode();
double lat =address.getLatitude();
double lon= address.getLongitude();
			
            result.append(locality+" ");
            result.append(city+" "+ region_code+" ");
result.append(zipcode);

        }
    } catch (IOException e) {
        Log.e("tag", e.getMessage());
    }

    return result.toString();
}
 
Example #8
Source Project: MuslimMateAndroid   Author: fekracomputers   File: SelectLocationTabsActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);

            StringBuilder strReturnedAddress = new StringBuilder("");

            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            strAdd = strReturnedAddress.toString();
            Log.w("My Current loction address", "" + strReturnedAddress.toString());
        } else {
            Log.w("My Current loction address", "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w("My Current loction address", "Canont get Address!");
    }
    return strAdd;
}
 
Example #9
Source Project: open-rmbt   Author: alladin-IT   File: MapLocationRequestTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Address doInBackground(String... params) {
   	final Geocoder geocoder = new Geocoder(activity);
  		List<Address> addressList;
	try {
		addressList = geocoder.getFromLocationName(params[0], 1);
   		if (addressList != null && addressList.size() > 0) {
   			return addressList.get(0);
   		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
  		return null;
}
 
Example #10
Source Project: PHONK   Author: victordiaz   File: PLocation.java    License: GNU General Public License v3.0 6 votes vote down vote up
@PhonkMethod(description = "Get the location name of a given latitude and longitude", example = "")
@PhonkMethodParam(params = {"latitude", "longitude"})
public String getLocationName(double lat, double lon) {
    String gpsLocation = "";
    Geocoder gcd = new Geocoder(getContext(), Locale.getDefault());
    List<Address> addresses;
    try {
        addresses = gcd.getFromLocation(lat, lon, 1);
        gpsLocation = addresses.get(0).getLocality();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return gpsLocation;
}
 
Example #11
Source Project: Compass   Author: tranleduy2000   File: GetDataTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected LocationData doInBackground(Location... params) {
    Location location = params[0];

    double longitude = location.getLongitude();
    double latitude = location.getLatitude();

    LocationData weatherData = new LocationData();
    weatherData.setLongitude((float) longitude);
    weatherData.setLatitude((float) latitude);
    weatherData.setAltitude(location.getAltitude());

    try {
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            weatherData.setAddressLine(address.getAddressLine(0));
        }
        WeatherManager.getWeatherData(location, weatherData);
    } catch (Exception e) {
        return null;
    }
    return weatherData;
}
 
Example #12
Source Project: appinventor-extensions   Author: mit-cml   File: LocationSensor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new LocationSensor component with a default state of <code>enabled</code>.
 *
 * @param container  ignored (because this is a non-visible component)
 * @param enabled  true if the LocationSensor is enabled by default, otherwise false.
 */
public LocationSensor(ComponentContainer container, boolean enabled) {
  super(container.$form());
  this.enabled = enabled;
  handler = new Handler();
  // Set up listener
  form.registerForOnResume(this);
  form.registerForOnStop(this);

  // Initialize sensor properties (60 seconds; 5 meters)
  timeInterval = 60000;
  distanceInterval = 5;

  // Initialize location-related fields
  Context context = container.$context();
  geocoder = new Geocoder(context);
  locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
  locationCriteria = new Criteria();
  myLocationListener = new MyLocationListener();
  allProviders = new ArrayList<String>();
  // Do some initialization depending on the initial enabled state
  Enabled(enabled);
}
 
Example #13
Source Project: apigee-android-sdk   Author: apigee   File: EventsActivity.java    License: Apache License 2.0 6 votes vote down vote up
public EventContainer(Entity entity) {
    this.eventName = entity.getStringProperty("eventName");
    JsonNode locationObject= (JsonNode) entity.getProperties().get("location");
    if( locationObject != null && Geocoder.isPresent() ) {
        Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
        try {
            List<Address> addressList = myLocation.getFromLocation(locationObject.get("latitude").doubleValue(), locationObject.get("longitude").doubleValue(), 1);
            if( addressList != null && addressList.size() > 0 ) {
                Address locationAddress = addressList.get(0);
                this.eventLocation = locationAddress.getLocality() + ", " + locationAddress.getAdminArea();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #14
Source Project: SamLocationAndGeocoding   Author: kingsammalik   File: LocationAddress.java    License: MIT License 6 votes vote down vote up
public Address getAddressFromLocation(final double latitude, final double longitude,
                                      final Context context) {

    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    try {
        List<Address> addressList = geocoder.getFromLocation(
                latitude, longitude, 1);
        if (addressList != null && addressList.size() > 0) {
            address = addressList.get(0);

        }
    } catch (IOException e) {

        Log.e(TAG, "Unable connect to Geocoder", e);
    }
    return address;


}
 
Example #15
Source Project: open-quartz   Author: jaredsburrows   File: LocationProvider.java    License: Apache License 2.0 6 votes vote down vote up
public LocationProvider(Context context) {
    mLocationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    mGeocoder = new Geocoder(context);

    final Criteria criteria = new Criteria();
    mBestProvider = mLocationManager.getBestProvider(criteria,
            true);

    final List<String> providers = mLocationManager.getProviders(
            criteria, true);

    for (String provider : providers) {
        // mLocationManager.requestLocationUpdates(provider, 0, 0, this);
    }
}
 
Example #16
Source Project: analyzer-of-android-for-Apache-Weex   Author: weexteam   File: DefaultLocation.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get address info
 */
private Address getAddress(double latitude, double longitude) {
  if(WXEnvironment.isApkDebugable()) {
    WXLogUtils.d(TAG, "into--[getAddress] latitude:" + latitude + " longitude:" + longitude);
  }
  try {
    if (mWXSDKInstance == null || mWXSDKInstance.isDestroy()) {
      return null;
    }
    Geocoder gc = new Geocoder(mWXSDKInstance.getContext());
    List<Address> list = gc.getFromLocation(latitude, longitude, 1);
    if (list != null && list.size() > 0) {
      return list.get(0);
    }
  } catch (Exception e) {
    WXLogUtils.e(TAG, e);
  }
  return null;
}
 
Example #17
Source Project: SampleApp   Author: saveendhiman   File: LocationHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * to get latitude and longitude of an address
 *
 * @param strAddress address string
 * @return lat and lng in comma separated string
 */
public String getLocationFromAddress(String strAddress) {

    Geocoder coder = new Geocoder(mContext);
    List<Address> address;

    try {
        address = coder.getFromLocationName(strAddress, 1);
        if (address == null) {
            return null;
        }
        Address location = address.get(0);
        double lat = location.getLatitude();
        double lng = location.getLongitude();

        return lat + "," + lng;
    } catch (Exception e) {
        return null;
    }
}
 
Example #18
Source Project: lunzi   Author: macouen   File: MapLocationUtil.java    License: Apache License 2.0 6 votes vote down vote up
private Address getAddressByGeoPoint(Location location) {
    Address result = null;
    // 先将Location转换为GeoPoint
    // GeoPoint gp=getGeoByLocation(location);
    try {
        if (location != null) {
            // 获取Geocoder,通过Geocoder就可以拿到地址信息
            Geocoder gc = new Geocoder(mContext, Locale.CHINA);
            List<Address> lstAddress = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (lstAddress.size() > 0) {
                result = lstAddress.get(0);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example #19
Source Project: PocketMaps   Author: junjunguo   File: GeocoderGlobal.java    License: MIT License 6 votes vote down vote up
public List<Address> find_google(Context context, String searchS)
{
  stopping = false;
  log("Google geocoding started");
  Geocoder geocoder = new Geocoder(context, locale);
  if (!Geocoder.isPresent()) { return null; }
  try
  {
    List<Address> result = geocoder.getFromLocationName(searchS, 50);
    return result;
  }
  catch (IOException e)
  {
    e.printStackTrace();
  }
  return null;
}
 
Example #20
Source Project: PowerSwitch_Android   Author: Power-Switch   File: MapViewHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Find a address description for a given coordinate
 *
 * @param latLng coordinate
 * @return address description
 * @throws AddressNotFoundException
 */
public String findAddress(LatLng latLng) throws AddressNotFoundException {
    /* get latitude and longitude from the address */
    Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 5);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);


            String addressAsString = address.getAddressLine(0);

            Log.d("Address; ", addressAsString);
            return addressAsString;
        } else {
            throw new AddressNotFoundException("latitude: " + latLng.latitude + ", longitude: " + latLng.longitude);
        }
    } catch (IOException e) {
        Log.e(e);
    }

    return null;
}
 
Example #21
Source Project: PowerSwitch_Android   Author: Power-Switch   File: MapViewHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Find Coordinates for a given address
 *
 * @param address address as text
 * @return coordinate near the given address
 * @throws AddressNotFoundException
 */
public LatLng findCoordinates(String address) throws CoordinatesNotFoundException {
    /* get latitude and longitude from the address */
    Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocationName(address, 5);
        if (addresses.size() > 0) {
            Double lat = (addresses.get(0).getLatitude());
            Double lon = (addresses.get(0).getLongitude());

            Log.d("lat-lon", lat + "......." + lon);
            final LatLng location = new LatLng(lat, lon);
            return location;
        } else {
            throw new CoordinatesNotFoundException(address);
        }
    } catch (IOException e) {
        Log.e(e);
    }

    return null;
}
 
Example #22
Source Project: SwipeableCard   Author: michelelacorte   File: SwipeableCardAdapter.java    License: Apache License 2.0 6 votes vote down vote up
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("SwipeableCardAdapter", "Error tryng to retrieve street name from lat long");
    }
    return streetName;
}
 
Example #23
Source Project: SwipeableCard   Author: michelelacorte   File: SwipeableCard.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get street name from latitude and longitude
 * @param lat latitude double
 * @param lon longitude double
 * @param context Context
 * @return String street name
 */
public String getStreetNameFromLatLong(double lat, double lon, Context context)
{
    String streetName = null;
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);

        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder();
            for (int j = 0; j < returnedAddress.getMaxAddressLineIndex(); j++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(j)).append("");
            }
            streetName = strReturnedAddress.toString();
        }
    } catch (IOException e) {
        Log.e("SwipeableCard", "Error tryng to retrieve street name from lat long");
    }
    return streetName;
}
 
Example #24
Source Project: PhoneProfilesPlus   Author: henrichg   File: LocationGeofenceEditorActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void refreshActivity(boolean setMapCamera) {
    boolean enableAddressButton = false;
    if (mLocation != null) {
        // Determine whether a geo-coder is available.
        if (Geocoder.isPresent()) {
            startIntentService(false);
            enableAddressButton = true;
        }
    }
    if (addressButton.isEnabled())
        GlobalGUIRoutines.setImageButtonEnabled(enableAddressButton, addressButton, getApplicationContext());
    String name = geofenceNameEditText.getText().toString();

    updateEditedMarker(setMapCamera);

    okButton.setEnabled((!name.isEmpty()) && (mLocation != null));
}
 
Example #25
Source Project: OpenFit   Author: jareddlc   File: LocationInfo.java    License: MIT License 6 votes vote down vote up
public static void init(Context cntxt) {
    Log.d(LOG_TAG, "Initializing Location");
    context = cntxt;

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
        // Impossible to call requestPermissions from a service. It has to be done from an activity => stop the service
        context.sendBroadcast(new Intent(OpenFitIntent.INTENT_SERVICE_STOP));
    } else {
        // Permission has already been granted

        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        geocoder = new Geocoder(context, Locale.getDefault());

        updateLastKnownLocation();
        listenForLocation(true);
    }
}
 
Example #26
Source Project: open-quartz   Author: jaredsburrows   File: ChronometerView.java    License: Apache License 2.0 6 votes vote down vote up
public ChronometerView(Context context) {
    this(context, null, 0);

    final StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    geocoder = new Geocoder(context);

    criteria = new Criteria();
    best = locationManager.getBestProvider(criteria, true);
    location = locationManager.getLastKnownLocation(best);

    providers = locationManager.getProviders(criteria, true);

    for (String provider : providers) {
        locationManager.requestLocationUpdates(provider, 0, 0, this);
        Log.e("TAG", "" + provider);
    }

}
 
Example #27
Source Project: tlplib   Author: tinylabproductions   File: Bridge.java    License: MIT License 6 votes vote down vote up
public static String countryCodeFromLastKnownLocation() throws IOException {
  Activity current = UnityPlayer.currentActivity;
  LocationManager locationManager =
          (LocationManager) current.getSystemService(Context.LOCATION_SERVICE);
  Location location =
          locationManager
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  if (location != null && Geocoder.isPresent()) {
    Geocoder gcd = new Geocoder(current, Locale.getDefault());
    List<Address> addresses;
    addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

    if (addresses != null && !addresses.isEmpty()) {
      Address address = addresses.get(0);
      return address.getCountryCode();
    }
  }
  return null;
}
 
Example #28
Source Project: kickflip-android-sdk   Author: Kickflip   File: Kickflip.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method for attaching the current reverse geocoded device location to a given
 * {@link io.kickflip.sdk.api.json.Stream}
 *
 * @param context  the host application {@link android.content.Context}
 * @param stream   the {@link io.kickflip.sdk.api.json.Stream} to attach location to
 * @param eventBus an {@link com.google.common.eventbus.EventBus} to be notified of the complete action
 */
public static void addLocationToStream(final Context context, final Stream stream, final EventBus eventBus) {
    DeviceLocation.getLastKnownLocation(context, false, new DeviceLocation.LocationResult() {
        @Override
        public void gotLocation(Location location) {
            stream.setLatitude(location.getLatitude());
            stream.setLongitude(location.getLongitude());

            try {
                Geocoder geocoder = new Geocoder(context);
                Address address = geocoder.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1).get(0);
                stream.setCity(address.getLocality());
                stream.setCountry(address.getCountryName());
                stream.setState(address.getAdminArea());
                if (eventBus != null) {
                    eventBus.post(new StreamLocationAddedEvent());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

}
 
Example #29
Source Project: FimiX8-RE   Author: wladimir-computin   File: GglMapLocationManager.java    License: MIT License 5 votes vote down vote up
private void getCity(Location location) {
    List<Address> addList = null;
    try {
        addList = new Geocoder(this.context).getFromLocation(location.getLatitude(), location.getLongitude(), 1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (addList != null && addList.size() > 0) {
        for (int i = 0; i < addList.size(); i++) {
            X8MapGetCityManager.locality = ((Address) addList.get(i)).getLocality();
        }
    }
    this.state = 0;
}
 
Example #30
Source Project: android_9.0.0_r45   Author: lulululbj   File: LocationBasedCountryDetector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @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;
}