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.hoccer.api.android.LinccLocationManager.java

public Address getAddress(Location location) throws IOException {
    if (location == null) {
        return new Address(null);
    }//from w  ww  .  j  av  a2  s  .  co  m

    Geocoder gc = new Geocoder(mContext);

    Address address = null;
    List<Address> addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
    if (addresses.size() > 0) {
        address = addresses.get(0);
    }
    return address;
}

From source file:com.alaskalinuxuser.mymemoriableplacesapp.MapsActivity.java

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;/*from  w  w w.java2  s .c  om*/
    mMap.clear();

    Double lat = Double.parseDouble(latPlace);
    Double lon = Double.parseDouble(longPlace);

    LatLng currentPlace = new LatLng(lat, lon);
    mMap.addMarker(new MarkerOptions().position(currentPlace).title(namePlace)
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
    mMap.moveCamera(CameraUpdateFactory.zoomTo(10));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentPlace));

    mMap.setOnMapLongClickListener(new OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng arg0) {

            mMap.addMarker(new MarkerOptions().position(arg0).title("new location")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

            Double lati = (arg0.latitude);
            Double loni = (arg0.longitude);
            String aLatPlace = lati.toString();
            String aLongPlace = loni.toString();

            Geocoder myGeo = new Geocoder(getApplicationContext(), Locale.getDefault());

            try {
                List<Address> myAddresses = myGeo.getFromLocation(lati, loni, 1);

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

                    // FOR TESTING //Log.i("WJH", myAddresses.get(0).toString());

                    myNewLocal = myAddresses.get(0).getAddressLine(0) + ", "
                            + myAddresses.get(0).getAddressLine(1);

                } else {

                    myNewLocal = "";

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

            Intent returnIntent = getIntent();
            returnIntent.putExtra("anamePlace", myNewLocal);
            returnIntent.putExtra("alatPlace", aLatPlace);
            returnIntent.putExtra("alongPlace", aLongPlace);
            setResult(Activity.RESULT_OK, returnIntent);
            finish();

        }
    });

}

From source file:com.sanjaydalvi.spacestationlocator.MainActivity.java

public void showLocation() {
    // get latitude and longitude values and fetch location data such as city and country
    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
    try {//  ww w . j a va  2  s.  co  m
        List<Address> addresses = geocoder.getFromLocation(currentLocation.latitude, currentLocation.longitude,
                1);
        if (addresses.size() != 0) {
            String city = addresses.get(0).getLocality();
            //String state = addresses.get(0).getAdminArea();
            //String zip = addresses.get(0).getPostalCode();
            String country = addresses.get(0).getCountryName();
            // Toast.makeText(getApplicationContext(), "Current location : " + city + ", " + country, Toast.LENGTH_SHORT).show();
            locationTextView.setText("Current location : " + city + ", " + country);
            //Snackbar.make(getWindow().getDecorView().getRootView(), "Current location : " + city + ", " + country, Snackbar.LENGTH_LONG).setAction("Action", null).show();
        } else {
            // Toast.makeText(getApplicationContext(), "Current location : Ocean.", Toast.LENGTH_SHORT).show();
            locationTextView.setText("Current location : Over a water body.");
        }
    } catch (IOException e) {
        Log.d("space ship locator", e.getMessage());
    }
}

From source file:semanticweb.hws14.movapp.activities.Criteria.java

private void useLocationData(Location location) {
    //Receive the location Data
    AlertDialog ad = new AlertDialog.Builder(that).create();
    ad.setCancelable(false); // This blocks the 'BACK' button
    Geocoder geocoder = new Geocoder(that, Locale.ENGLISH);
    try {//from  ww w  . j a v  a2 s .  co  m
        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            final String strReturnedAdress = returnedAddress.getLocality();
            ad.setMessage("You are in: " + strReturnedAdress + "\nUse this location for the search?");

            ad.setButton(DialogInterface.BUTTON_POSITIVE, "YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    if (tabPosition == 0) {
                        MovieCriteria currentFragmet = (MovieCriteria) getFragmentByPosition(tabPosition);
                        currentFragmet.setGPSLocation(strReturnedAdress);
                    } else if (tabPosition == 1) {
                        ActorCriteria currentFragmet = (ActorCriteria) getFragmentByPosition(tabPosition);
                        currentFragmet.setGPSLocation(strReturnedAdress);
                    }

                    dialog.dismiss();
                }
            });

            ad.setButton(DialogInterface.BUTTON_NEGATIVE, "NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        } else {
            ad.setMessage("No Address returned!");
            ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    } catch (IOException e) {
        e.printStackTrace();
        ad.setMessage("Can not get Address!");
        ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    ad.show();
    setProgressBarIndeterminateVisibility(false);
    locMgr.removeUpdates(locListner);
}

From source file:com.android.deskclock.worldclock.CityAndTimeZoneLocator.java

private String resolveCity() {
    try {//from ww w  .j  a va 2s  .c om
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(),
                1);
        if (addresses.size() > 0) {
            return addresses.get(0).getLocality();
        } else {
            Log.w(TAG, "No city data");
        }
    } catch (IOException e) {
        Log.e(TAG, "Failed to retrieve city", e);
    }
    return null;
}

From source file:com.laocuo.weather.presenter.impl.LocationPresenter.java

private String saveCityByLocation(Location l) {
    String city = null;//from w w w  .  j  av a  2  s  .  co m
    Double latitude = l.getLatitude();
    Double longitude = l.getLongitude();
    Geocoder gc = new Geocoder(mContext, Locale.getDefault());
    List<Address> addressList = null;
    try {
        addressList = gc.getFromLocation(latitude, longitude, 10);
        Address address = addressList.get(0);
        L.d("Locality:" + address.getLocality());
        city = address.getLocality();
        if (TextUtils.isEmpty(city) == false) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
            editor.putString(CITY_KEY, city);
            editor.commit();
        }
    } catch (IOException e) {
        e.printStackTrace();
        mView.getLocationFail();
    } finally {
        return city;
    }
}

From source file:com.example.android.animationsdemo.RecentQueryActivity.java

public void getAddressByLocation(Location location) {
    String result = "No Result";
    try {/*ww  w. j a  v  a  2s .c  om*/
        if (location != null) {
            Double longitude = location.getLongitude(); //?
            Double latitude = location.getLatitude(); //?

            //Geocoder: Android 8 ?
            Geocoder gc = new Geocoder(this, Locale.TRADITIONAL_CHINESE); //?:??
            //??
            List<Address> lstAddress = gc.getFromLocation(latitude, longitude, 5);
            if (lstAddress.size() > 0) {
                result = "";
                for (int i = 0; i < lstAddress.size(); i++) {
                    result = result + i + " : " + "\n";
                    result = result + "Address: " + lstAddress.get(0).getAddressLine(0) + "\n";
                    result = result + "Locality: " + lstAddress.get(0).getLocality() + "\n";
                    result = result + "AdminArea: " + lstAddress.get(0).getAdminArea() + "\n";
                    result = result + "Country: " + lstAddress.get(0).getCountryName() + "\n";
                    result = result + "PostalCode: " + lstAddress.get(0).getPostalCode() + "\n";
                    result = result + "Feature: " + lstAddress.get(0).getFeatureName() + "\n\n";

                    //result = result + lstAddress.get(i).getAddressLine(0) + "\n";
                    //result = result + lstAddress.get(i).getPostalCode() + "\n";
                }
            }
            resultTextView.setText(result);
        }
    } catch (Exception e) {
        DKLog.e(TAG, Trace.getCurrentMethod() + e.toString());
    }
}

From source file:it.ms.theing.loquitur.functions.LocationInterface.java

/**
 * Get a string with the location.// ww w.j  a  va2s.c  o  m
 * @param lat
 * latitude
 * @param lon
 * longitude
 * @return
 * location or empty string
 */
@JavascriptInterface
public String geoCoder(float lat, float lon) {
    try {
        Geocoder geo = new Geocoder(context);
        if (!geo.isPresent())
            return "";
        List<Address> addresses = geo.getFromLocation(lat, lon, 1);
        if (addresses == null)
            return "";
        if (addresses.size() > 0) {
            JSONArray ja = new JSONArray();
            if (addresses.get(0).getFeatureName() != null)
                ja.put(addresses.get(0).getFeatureName());
            else
                ja.put("");
            if (addresses.get(0).getAddressLine(0) != null)
                ja.put(addresses.get(0).getAddressLine(0));
            else
                ja.put("");
            if (addresses.get(0).getLocality() != null)
                ja.put(addresses.get(0).getLocality());
            else
                ja.put("");
            if (addresses.get(0).getAdminArea() != null)
                ja.put(addresses.get(0).getAdminArea());
            else
                ja.put("");
            if (addresses.get(0).getCountryName() != null)
                ja.put(addresses.get(0).getCountryName());
            else
                ja.put("");
            return ja.toString();
        }
    } catch (Exception e) {
    }
    return "";
}

From source file:org.microg.gms.ui.PlacePickerActivity.java

@Override
public void onMapEvent(Event event, MapPosition position) {
    place.viewport = GmsMapsTypeHelper.toLatLngBounds(mapView.map().viewport().getBBox(null, 0));
    resultIntent.putExtra(LocationConstants.EXTRA_FINAL_BOUNDS, place.viewport);
    place.latLng = GmsMapsTypeHelper.toLatLng(position.getGeoPoint());
    place.name = "";
    place.address = "";
    updateInfoText();// w  w  w.j  ava2s  .com
    if (geocoderInProgress.compareAndSet(false, true)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    LatLng ll = null;
                    while (ll != place.latLng) {
                        ll = place.latLng;
                        Thread.sleep(1000);
                    }
                    Geocoder geocoder = new Geocoder(PlacePickerActivity.this);
                    List<Address> addresses = geocoder.getFromLocation(place.latLng.latitude,
                            place.latLng.longitude, 1);
                    if (addresses != null && !addresses.isEmpty()
                            && addresses.get(0).getMaxAddressLineIndex() > 0) {
                        Address address = addresses.get(0);
                        StringBuilder sb = new StringBuilder(address.getAddressLine(0));
                        for (int i = 1; i < address.getMaxAddressLineIndex(); ++i) {
                            if (i == 1 && sb.toString().equals(address.getFeatureName())) {
                                sb = new StringBuilder(address.getAddressLine(i));
                                continue;
                            }
                            sb.append(", ").append(address.getAddressLine(i));
                        }
                        if (place.latLng == ll) {
                            place.address = sb.toString();
                            place.name = address.getFeatureName();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateInfoText();
                                }
                            });
                        }
                    }
                } catch (Exception ignored) {
                    Log.w(TAG, ignored);
                } finally {
                    geocoderInProgress.lazySet(false);
                }
            }
        }).start();
    }
}

From source file:cmu.troy.applogger.AppService.java

private void logApps(List<String> newApps, List<String> currentApps) throws IOException {
    /*// w  w w  . j a  v a 2  s . c  o  m
     * Empty newApps means current apps are the same with the last apps. So there is no need to
     * update last apps file or log file.
     */
    if (newApps == null || newApps.size() == 0)
        return;

    lastApps = currentApps;
    Date now = new Date();

    /* Append new Apps into log file */
    JSONObject job = new JSONObject();
    String id = String.valueOf(now.getTime());
    try {
        job.put(JSONKeys.id, id);
        job.put(JSONKeys.first, newApps.get(0));
        job.put(JSONKeys.log_type, JSONValues.OPEN_AN_APP);
        /* Log Location block */
        Location mLocation = null;
        if (mLocationClient.isConnected())
            mLocation = mLocationClient.getLastLocation();
        if (mLocation != null) {
            job.put(JSONKeys.loc_available, true);
            job.put(JSONKeys.latitude, mLocation.getLatitude());
            job.put(JSONKeys.longitude, mLocation.getLongitude());
            job.put(JSONKeys.location_accuracy, mLocation.getAccuracy());
            job.put(JSONKeys.location_updated_time, (new Date(mLocation.getTime())).toString());

            Date updateTime = new Date(mLocation.getTime());
            if ((updateTime.getTime() - now.getTime()) / 60000 > 5) {
                Tools.runningLog("Last location is too old, a location update is triggered.");
                LocationRequest request = new LocationRequest();
                request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                mLocationClient.requestLocationUpdates(request, new LocationListener() {
                    @Override
                    public void onLocationChanged(Location arg0) {
                    }
                });
            }

            if (lastLocation == null || lastAddress == null
                    || lastLocation.distanceTo(mLocation) > Tools.SMALL_DISTANCE) {
                /* Log Address if location is available */
                Geocoder geocoder = new Geocoder(this, Locale.getDefault());
                List<Address> addresses = null;
                addresses = geocoder.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1);
                if (addresses != null && addresses.size() > 0) {
                    job.put(JSONKeys.addr_available, true);
                    Address address = addresses.get(0);
                    lastAddress = address;
                    job.put(JSONKeys.address,
                            address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "");
                    job.put(JSONKeys.city, address.getLocality());
                    job.put(JSONKeys.country, address.getCountryName());
                } else {
                    job.put(JSONKeys.addr_available, false);
                }
            } else {
                job.put(JSONKeys.addr_available, true);
                job.put(JSONKeys.address,
                        lastAddress.getMaxAddressLineIndex() > 0 ? lastAddress.getAddressLine(0) : "");
                job.put(JSONKeys.city, lastAddress.getLocality());
                job.put(JSONKeys.country, lastAddress.getCountryName());
            }
            lastLocation = mLocation;
        } else {
            if (!mLocationClient.isConnecting())
                mLocationClient.connect();
            job.put(JSONKeys.loc_available, false);
        }
    } catch (JSONException e) {
        Log.e("JSON", e.toString());
    }
    Tools.logJsonNewBlock(job);
}