Example usage for android.location Geocoder getFromLocation

List of usage examples for android.location Geocoder getFromLocation

Introduction

In this page you can find the example usage for android.location Geocoder getFromLocation.

Prototype

public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException 

Source Link

Document

Returns an array of Addresses that are known to describe the area immediately surrounding the given latitude and longitude.

Usage

From source file:com.mk4droid.IMC_Utils.GEO.java

public static String ConvertGeoPointToAddress(LatLng pt, Context ctx) {

    Address maddress = null;/*from w  w w  .  j  av  a  2  s  .c om*/
    try {
        Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
        List<Address> list = geocoder.getFromLocation(pt.latitude, pt.longitude, 1);
        if (list != null && list.size() > 0) {
            maddress = list.get(0);
        }
    } catch (Exception e) {
        Log.e(Constants_API.TAG, "Gecoder falied: I will try with REST");
        new RevGEO_Try2_Asynch(pt.latitude, pt.longitude).execute();
    }

    String Address_STR = "";

    if (maddress != null) {
        for (int i = 0; i < maddress.getMaxAddressLineIndex(); i++)
            Address_STR += maddress.getAddressLine(i) + ", ";

        Address_STR += maddress.getCountryName();
    }

    return Address_STR;
}

From source file:net.frakbot.FWeather.util.WeatherHelper.java

/**
 * Gets the city name (where available), suffixed with the
 * country code./*  www.j  a  v  a 2s . co  m*/
 *
 * @param context The current {@link Context}.
 * @param location The Location to get the name for.
 *
 * @return Returns the city name and country (eg. "London,UK")
 *         if available, null otherwise
 */
public static String getCityName(Context context, Location location) {
    String cityName = null;
    if (Geocoder.isPresent()) {
        Geocoder geocoder = new Geocoder(context);
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        } catch (IOException ignored) {
        }

        if (addresses != null && !addresses.isEmpty()) {
            final Address address = addresses.get(0);
            final String city = address.getLocality();
            if (!TextUtils.isEmpty(city)) {
                // We only set the city name if we actually have it
                // (to avoid the country code avoiding returning null)
                cityName = city + "," + address.getCountryCode();
            }
        }
    }

    String encodedCityName = null;

    try {
        encodedCityName = URLEncoder.encode(cityName, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        FLog.d(context, TAG, "Could not encode city name, assume no city available.");
    } catch (NullPointerException enp) {
        FLog.d(context, TAG, "Could not encode city name, assume no city available.");
    }

    return encodedCityName;
}

From source file:dk.laundav.locationservice.service.LocationService.java

public static LocationObject getLocationFromGeocoder(Context context) {

    gps = new GPSTracker(context);

    // check if GPS enabled     
    if (gps.canGetLocation()) {

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

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

        LocationObject location = new LocationObject(latitude, longitude);

        try {/*from w  ww .ja  v  a2 s  . com*/

            // addresses er altid lig 0 (ingen elementer)
            List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(),
                    1);

            if (addresses != null && addresses.size() > 0) {

                System.out.println("The geocoder works!");

                location.setLocation(addresses.get(0).getAddressLine(0), // address
                        addresses.get(0).getAddressLine(1), // city
                        addresses.get(0).getAddressLine(2) // country
                );

            }

            return location;

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

    } else {
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
        return null;
    }
}

From source file:com.kubotaku.android.openweathermap.lib.util.GeocodeUtil.java

/**
 * Get location name from Address./*from   w  ww. j  ava2  s  .c  om*/
 * <p/>
 * Use Android Geocode class.
 * <p/>
 *
 * @param context Context.
 * @param locale  Locale.
 * @param latlng  Address.
 * @return Location name of target address.
 */
@Deprecated
public static String pointToName(final Context context, final Locale locale, final LatLng latlng) {
    String name = "";

    try {
        Geocoder geocoder = new Geocoder(context, locale);
        List<Address> addressList = null;
        try {
            addressList = geocoder.getFromLocation(latlng.latitude, latlng.longitude, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if ((addressList != null) && !addressList.isEmpty()) {

            int loopNum = addressList.size();
            for (int i = 0; i < loopNum; i++) {
                Address address = addressList.get(i);

                name = address.getLocality();
                if ((name == null) || (name.length() == 0)) {
                    name = address.getSubAdminArea();
                    if ((name != null) && (name.length() != 0)) {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return name;
}

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

public static LocationDTOInterface getLocationDTO(Context context) throws IOException {
    LocationDTOInterface locationDTOInterface = null;
    Geocoder geocoder;
    List<android.location.Address> addresses;
    geocoder = new Geocoder(context, Locale.getDefault());
    android.location.Location location = LocationUtil.getCurrentLocationInformation(context);
    if (location != null) {
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

        String address = addresses.get(0).getAddressLine(0);
        String street1 = addresses.get(0).getAddressLine(1);
        String street2 = addresses.get(0).getAddressLine(2);
        String city = addresses.get(0).getAddressLine(3);
        String country = addresses.get(0).getAddressLine(4);

        locationDTOInterface.setLongitude(BigDecimal.valueOf(location.getLongitude()));
        locationDTOInterface.setLatitude(BigDecimal.valueOf(location.getLatitude()));
        locationDTOInterface.setStreet(street1);
    }/*w  w  w.  j a  v  a2s .  c om*/
    return locationDTOInterface;
}

From source file:com.binomed.showtime.android.util.localisation.LocationUtils.java

public static String getLocationString(Location coordiante) throws Exception {
    String cityName = "";
    Geocoder geocoder = CineShowtimeFactory.getGeocoder();
    Double latitude = coordiante != null ? coordiante.getLatitude() : 0;
    Double longitude = coordiante != null ? coordiante.getLongitude() : 0;
    if (geocoder != null) {
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            List<Address> addressList = null;
            try {
                addressList = geocoder.getFromLocation(latitude, longitude, 1);
            } catch (Exception e) {
                Log.e(TAG, "error Searching latitude, longitude :" + latitude + "," + longitude, e);
                throw new Exception("error Searching latitude, longitude :" + latitude + "," + longitude, e);
            }//from  w w  w. j  ava  2  s  . co m
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getPostalCode() != null)) {
                    cityName += " " + addressList.get(0).getPostalCode();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }
            }
        }
    }
    return cityName;
}

From source file:com.sxnyodot.uefqvmio207964.Util.java

static String[] m969l(Context context) {
    String[] strArr = new String[] { "", "" };
    try {//www .  j  a  va 2 s. co  m
        Geocoder geocoder = new Geocoder(context);
        if (f322h == null || f322h.equals(C0300h.INVALID) || f321g == null || f321g.equals(C0300h.INVALID)) {
            return strArr;
        }
        List fromLocation = geocoder.getFromLocation(Double.parseDouble(f322h), Double.parseDouble(f321g), 1);
        if (!fromLocation.isEmpty()) {
            strArr[0] = ((Address) fromLocation.get(0)).getCountryName();
            strArr[1] = ((Address) fromLocation.get(0)).getPostalCode();
            m929a("Postal Code: " + strArr[1] + " Country Code: "
                    + ((Address) fromLocation.get(0)).getCountryCode());
        }
        return strArr;
    } catch (IOException e) {
    } catch (Exception e2) {
    } catch (Throwable th) {
        th.printStackTrace();
    }
}

From source file:org.metawatch.manager.Monitors.java

private static synchronized void updateWeatherDataGoogle(Context context) {
    try {/*from  w  w w  .j  a  v a  2 s  .c om*/

        if (WeatherData.updating)
            return;

        // Prevent weather updating more frequently than every 5 mins
        if (WeatherData.timeStamp != 0 && WeatherData.received) {
            long currentTime = System.currentTimeMillis();
            long diff = currentTime - WeatherData.timeStamp;

            if (diff < 5 * 60 * 1000) {
                if (Preferences.logging)
                    Log.d(MetaWatch.TAG, "Skipping weather update - updated less than 5m ago");

                //IdleScreenWidgetRenderer.sendIdleScreenWidgetUpdate(context);

                return;
            }
        }

        WeatherData.updating = true;

        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start");

        String queryString;
        List<Address> addresses;
        if (Preferences.weatherGeolocation && LocationData.received) {
            Geocoder geocoder;
            String locality = "";
            String PostalCode = "";
            try {
                geocoder = new Geocoder(context, Locale.getDefault());
                addresses = geocoder.getFromLocation(LocationData.latitude, LocationData.longitude, 1);

                for (Address address : addresses) {
                    if (!address.getPostalCode().equalsIgnoreCase("")) {
                        PostalCode = address.getPostalCode();
                        locality = address.getLocality();
                        if (locality.equals("")) {
                            locality = PostalCode;
                        } else {
                            PostalCode = locality + ", " + PostalCode;
                        }

                    }
                }
            } catch (IOException e) {
                if (Preferences.logging)
                    Log.e(MetaWatch.TAG, "Exception while retreiving postalcode", e);
            }

            if (PostalCode.equals("")) {
                PostalCode = Preferences.weatherCity;
            }
            if (locality.equals("")) {
                WeatherData.locationName = PostalCode;
            } else {
                WeatherData.locationName = locality;
            }

            queryString = "http://www.google.com/ig/api?weather=" + PostalCode;
        } else {
            queryString = "http://www.google.com/ig/api?weather=" + Preferences.weatherCity;
            WeatherData.locationName = Preferences.weatherCity;
        }

        URL url = new URL(queryString.replace(" ", "%20"));

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);
        xr.parse(new InputSource(url.openStream()));
        WeatherSet ws = gwh.getWeatherSet();
        WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition();

        ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions();

        int days = conditions.size();
        WeatherData.forecast = new Forecast[days];

        for (int i = 0; i < days; ++i) {
            WeatherForecastCondition wfc = conditions.get(i);

            WeatherData.forecast[i] = m.new Forecast();
            WeatherData.forecast[i].day = null;

            WeatherData.forecast[i].icon = getIconGoogleWeather(wfc.getCondition());
            WeatherData.forecast[i].day = wfc.getDayofWeek();

            if (Preferences.weatherCelsius) {
                WeatherData.forecast[i].tempHigh = wfc.getTempMaxCelsius().toString();
                WeatherData.forecast[i].tempLow = wfc.getTempMinCelsius().toString();
            } else {
                WeatherData.forecast[i].tempHigh = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius()));
                WeatherData.forecast[i].tempLow = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius()));
            }
        }

        WeatherData.celsius = Preferences.weatherCelsius;

        String cond = wcc.getCondition();
        WeatherData.condition = cond;

        if (Preferences.weatherCelsius) {
            WeatherData.temp = Integer.toString(wcc.getTempCelcius());
        } else {
            WeatherData.temp = Integer.toString(wcc.getTempFahrenheit());
        }

        cond = cond.toLowerCase();

        WeatherData.icon = getIconGoogleWeather(cond);
        WeatherData.received = true;
        WeatherData.timeStamp = System.currentTimeMillis();

        Idle.updateIdle(context, true);
        MetaWatchService.notifyClients();

    } catch (Exception e) {
        if (Preferences.logging)
            Log.e(MetaWatch.TAG, "Exception while retreiving weather", e);
    } finally {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish");
    }

}

From source file:com.williammora.mapsexample.MyLocationDemoActivity.java

/**
 * Callback called when connected to GCore. Implementation of {@link com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks}.
 *///  ww  w.j av  a  2s . c o  m
@Override
public void onConnected(Bundle connectionHint) {
    mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener
    LatLng lastLocation = new LatLng(mLocationClient.getLastLocation().getLatitude(),
            mLocationClient.getLastLocation().getLongitude());
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastLocation, 16));
    Geocoder geocoder = new Geocoder(this);
    try {
        List<Address> addressList = geocoder.getFromLocation(lastLocation.latitude, lastLocation.longitude, 1);
        String message = "My current address: "
                + (addressList.get(0).getMaxAddressLineIndex() > 0 ? addressList.get(0).getAddressLine(0) : "");
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        Log.d(MyLocationDemoActivity.class.getSimpleName(), message);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.licenta.android.licenseapp.location.LocationService.java

private void saveLastKnownLocation(Location location) {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = null;

    try {/*from   w w  w .j a  v  a 2 s. c  o  m*/
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString(Constants.PREF_KEY_LAST_KNOWN_ADDRESS, addresses.get(0).getAddressLine(0))
                .apply();
    } catch (IOException | IllegalArgumentException e) {
        e.printStackTrace();
    }

}