Example usage for android.location Geocoder Geocoder

List of usage examples for android.location Geocoder Geocoder

Introduction

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

Prototype

public Geocoder(Context context, Locale locale) 

Source Link

Document

Constructs a Geocoder whose responses will be localized for the given Locale.

Usage

From source file:com.tingbacke.wearmaps.MobileActivity.java

/**
 * Updates my location to currentLocation, moves the camera.
 *
 * @param location/*from   www . j a  v  a 2  s . co m*/
 */
private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(18).bearing(0).tilt(25)
            .build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    TextView myLatitude = (TextView) findViewById(R.id.textView);
    TextView myLongitude = (TextView) findViewById(R.id.textView2);
    TextView myAddress = (TextView) findViewById(R.id.textView3);
    ImageView myImage = (ImageView) findViewById(R.id.imageView);

    myLatitude.setText("Latitude: " + String.valueOf(latitude));
    myLongitude.setText("Longitude: " + String.valueOf(longitude));

    // Instantiating currDistance to get distance to destination from my location
    currDistance = getDistance(latitude, longitude, destLat, destLong);

    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);

    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");
            }

            // Hardcoded string which searches through strReturnedAddress for specifics
            // if statements decide which information will be displayed
            String fake = strReturnedAddress.toString();

            if (fake.contains("stra Varvsgatan")) {

                myAddress.setText("K3, Malm Hgskola" + "\n" + "Cykelparkering: 50m" + "\n" + "Dest: "
                        + Math.round(currDistance) + "m away");
                myImage.setImageResource(R.mipmap.kranen);

            } else if (fake.contains("Lilla Varvsgatan")) {

                myAddress.setText("Turning Torso" + "\n" + "Caf: 90m " + "\n" + "Dest: "
                        + Math.round(currDistance) + "m away");
                myImage.setImageResource(R.mipmap.turning);

            } else if (fake.contains("Vstra Varvsgatan")) {

                myAddress.setText("Kockum Fritid" + "\n" + "Bankomat: 47m" + "\n" + "Dest: "
                        + Math.round(currDistance) + "m away");
                myImage.setImageResource(R.mipmap.kockum);

            } else if (fake.contains("Stapelbddsgatan")) {

                myAddress.setText("Stapelbddsparken" + "\n" + "Toalett: 63m" + "\n" + "Dest: "
                        + Math.round(currDistance) + "m away");
                myImage.setImageResource(R.mipmap.stapel);

            } else if (fake.contains("Stora Varvsgatan")) {

                myAddress.setText("Media Evolution City" + "\n" + "Busshllplats: 94m" + "\n" + "Dest: "
                        + Math.round(currDistance) + "m away");
                myImage.setImageResource(R.mipmap.media);

            } else if (fake.contains("Masttorget")) {

                myAddress.setText("Ica Maxi" + "\n" + "Systembolaget: 87m" + "\n" + "Dest: "
                        + Math.round(currDistance) + "m away");
                myImage.setImageResource(R.mipmap.ica);

            } else if (fake.contains("Riggaregatan")) {

                myAddress.setText("Scaniabadet" + "\n" + "\n" + "Dest: " + Math.round(currDistance) + "m away");
                myImage.setImageResource(R.mipmap.scaniabadet);

            } else if (fake.contains("Dammfrivgen")) {
                //fakear Turning Torso p min adress fr tillfllet
                myAddress.setText("Turning Torso" + "\n" + "453m away");
                myImage.setImageResource(R.mipmap.turning);
            }

            //myAddress.setText(strReturnedAddress.toString()+ "Dest: " + Math.round(currDistance) + "m away");
            /*
                            // Added this Toast to display address ---> In order to find out where to call notification builder for wearable
                            Toast.makeText(MobileActivity.this, myAddress.getText().toString(),
                Toast.LENGTH_LONG).show();
            */
            //Here is where I call the notification builder for the wearable
            showNotification(1, "basic", getBasicNotification("myStack"));

        } else {
            myAddress.setText("No Address returned!");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        myAddress.setText("Cannot get Address!");
    }
}

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

public static LocationDTOInterface getLocationDTO(Context context) throws IOException {
    LocationDTOInterface locationDTOInterface = null;
    Geocoder geocoder;/*  ww w.j a v  a 2  s  . c o m*/
    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);
    }
    return locationDTOInterface;
}

From source file:me.trashout.fragment.TrashDetailFragment.java

/**
 * Setup trash data/*from www  .  j a v a  2  s .c om*/
 *
 * @param trash
 */
private void setupTrashData(Trash trash) {
    mImages = getFullScreenImagesFromTrash(trash);

    trashDetailStateName.setText(trash.getStatus().getStringResId());
    if (trash.isUpdateNeeded()) {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_status_unknown);
        trashDetailStateName.setText(R.string.trash_updateNeeded);
    } else if (Constants.TrashStatus.CLEANED.equals(trash.getStatus())) {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_activity_cleaned);
    } else if (Constants.TrashStatus.STILL_HERE.equals(trash.getStatus())
            && (trash.getUpdateHistory() == null || trash.getUpdateHistory().isEmpty())) {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_activity_reported);
    } else {
        trashDetailStateIcon.setImageResource(R.drawable.ic_trash_activity_updated);
    }

    trashDetailStateTime.setText(DateTimeUtils.getRoundedTimeAgo(getContext(), trash.getLastChangeDate()));

    trashDetailSizeIcon.setImageResource(trash.getSize().getIconResId());
    trashDetailSizeText.setText(trash.getSize().getStringResId());

    trashDetailTypeContainerFlexbox.removeAllViews();
    for (Constants.TrashType trashType : trash.getTypes()) {
        if (trashType != null) {
            FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.flexBasisPercent = 0.5f;
            trashDetailTypeContainerFlexbox.addView(getTrashTypeView(trashType), layoutParams);
        }
    }

    trashDetailHistoryContainer.removeAllViews();
    trashDetailHistoryContainer
            .addView(getTrashUpdateHistoryView(UpdateHistory.createLastUpdateHistoryFromTrash(trash),
                    (trash.getUpdateHistory() == null || trash.getUpdateHistory().isEmpty())));
    int updateHistoryOrder = 0;

    if (trash.getUpdateHistory() != null && !trash.getUpdateHistory().isEmpty()) {
        ArrayList<UpdateHistory> preparedUpdateHistory = prepareUpdateHistory(trash.getUpdateHistory());

        for (UpdateHistory updateHistory : preparedUpdateHistory) {

            if (trashDetailHistoryContainer.getChildCount() > 0)
                trashDetailHistoryContainer.addView(ViewUtils.getDividerView(getContext()));

            trashDetailHistoryContainer.addView(getTrashUpdateHistoryView(updateHistory,
                    updateHistoryOrder == preparedUpdateHistory.size() - 1));
            updateHistoryOrder++;
        }
    }

    trashDetailPhotoCount.setText(String.valueOf(mImages != null ? mImages.size() : 0));

    String accessibilityText;
    if (trash.getAccessibility() != null && !TextUtils
            .isEmpty(accessibilityText = trash.getAccessibility().getAccessibilityString(getContext()))) {
        trashDetailAccessibilityText.setText(accessibilityText);
    } else {
        trashDetailAccessibility.setVisibility(View.GONE);
        trashDetailAccessibilityText.setVisibility(View.GONE);
    }

    if (!TextUtils.isEmpty(trash.getNote())) {
        trashDetailAdditionalInformation.setVisibility(View.VISIBLE);
        trashDetailAdditionalInformationText.setVisibility(View.VISIBLE);

        trashDetailAdditionalInformationText.setText(trash.getNote());
    } else {
        trashDetailAdditionalInformation.setVisibility(View.GONE);
        trashDetailAdditionalInformationText.setVisibility(View.GONE);
    }

    if (trash.getGps() != null && trash.getGps().getArea() != null
            && !TextUtils.isEmpty(trash.getGps().getArea().getFormatedLocation())) {
        trashDetailPlace.setText(trash.getGps().getArea().getFormatedLocation());
    } else {
        Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
        new GeocoderTask(geocoder, trash.getGps().getLat(), trash.getGps().getLng(),
                new GeocoderTask.Callback() {
                    @Override
                    public void onAddressComplete(GeocoderTask.GeocoderResult geocoderResult) {
                        if (!TextUtils.isEmpty(geocoderResult.getFormattedAddress())) {
                            trashDetailPlace.setText(geocoderResult.getFormattedAddress());
                        } else {
                            trashDetailPlace.setVisibility(View.GONE);
                        }
                    }
                }).execute();
    }

    trashDetailPosition.setText(
            PositionUtils.getFormattedLocation(getContext(), trash.getGps().getLat(), trash.getGps().getLng()));

    trashDetailAccuracyLocationText
            .setText(String.format(getString(R.string.accuracy_formatter), trash.getGps().getAccuracy()));
    if (lastPosition != null)
        trashDetailLocationApproximately
                .setText(
                        String.format(getString(R.string.specific_distance_away_formatter),
                                lastPosition != null ? PositionUtils.getFormattedComputeDistance(getContext(),
                                        lastPosition, trash.getPosition()) : "?",
                                getString(R.string.global_distanceAttribute_away)));

    String mapUrl = PositionUtils.getStaticMapUrl(getActivity(), trash.getGps().getLat(),
            trash.getGps().getLng());
    try {
        URI mapUri = new URI(mapUrl.replace("|", "%7c"));
        Log.d(TAG, "setupTrashData: mapUrl = " + String.valueOf(mapUri.toURL()));
        GlideApp.with(this).load(String.valueOf(mapUri.toURL())).centerCrop().into(trashDetailMap);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    if (trash.getImages() != null && !trash.getImages().isEmpty()
            && ViewUtils.checkImageStorage(trash.getImages().get(0))) {
        StorageReference mImageRef = FirebaseStorage.getInstance()
                .getReferenceFromUrl(trash.getImages().get(0).getFullStorageLocation());
        GlideApp.with(this).load(mImageRef).centerCrop().transition(DrawableTransitionOptions.withCrossFade())
                .placeholder(R.drawable.ic_image_placeholder_rectangle).into(trashDetailImage);
    }

    trashDetailEventContainer.removeAllViews();
    if (trash.getEvents() != null && !trash.getEvents().isEmpty()) {
        trashDetailEventCardView.setVisibility(View.VISIBLE);
        trashDetailNoEvent.setVisibility(View.GONE);

        for (Event event : trash.getEvents()) {
            if (trashDetailEventContainer.getChildCount() > 0)
                trashDetailEventContainer.addView(ViewUtils.getDividerView(getContext()));

            trashDetailEventContainer.addView(getTrashEventView(event));
        }
    } else {
        trashDetailEventCardView.setVisibility(View.GONE);
        trashDetailNoEvent.setVisibility(View.VISIBLE);
    }
}

From source file:de.sindzinski.wetter.MainActivity.java

public String getLocationSetting(double lat, double lon) {
    String locationSetting = "";
    //locale must be set to us for getting english countey names
    Geocoder geoCoder = new Geocoder(this, Locale.US);
    StringBuilder builder = new StringBuilder();
    try {//from w  ww  .j a  va2s. c  o  m

        List<Address> address = geoCoder.getFromLocation(lat, lon, 1);
        //            String countryCode = address.get(0).getCountryCode();
        String country = address.get(0).getCountryName();
        //            String country = CountryCodes.getCountry(countryCode);
        String locality = address.get(0).getLocality();
        //            String adminArea = address.get(0).getAdminArea();
        builder.append(country).append("/")
                //                    .append(adminArea);
                .append(locality);

        locationSetting = builder.toString(); //This is the complete locationsetting as wug.
        locationSetting = wordFirstCap(locationSetting, "/");
    } catch (IOException e) {
    } catch (NullPointerException e) {
    }

    return locationSetting;
}

From source file:com.RSMSA.policeApp.OffenceReportForm.java

public String getAddress(double lat, double lng) {
    Geocoder geocoder = new Geocoder(OffenceReportForm.this, Locale.getDefault());
    String address = "";
    try {//  w ww.ja  v  a 2s  .  c  o  m
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        String add = "";
        if (obj.getAdminArea() != null) {
            add = add + obj.getAdminArea();
        }
        if (obj.getSubAdminArea() != null) {
            add = add + ", " + obj.getSubAdminArea();
        }
        if (obj.getAddressLine(0) != null) {
            add = add + ", " + obj.getAddressLine(0);
        }
        address = add;

        Log.v("IGA", "Address" + add);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {

    }
    return address;
}

From source file:com.jbsoft.farmtotable.FarmToTableActivity.java

private void getZipFromLocation(final Location location, final Context context) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    try {//from ww  w  .j av  a  2s .  c o  m
        List<Address> list = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (list != null && list.size() > 0) {
            Address address = list.get(0);
            // sending back first address line and locality
            zipcode = address.getPostalCode();
        }
    } catch (IOException e) {
        Log.e(TAG, "Impossible to connect to Geocoder", e);
    } finally {
    }
}

From source file:com.israel_fl.smartadaptweather.activities.MainActivity.java

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.d(TAG, "onConnected called");

    try {/*from  www .j  ava  2s . c  o m*/
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    } catch (SecurityException e) {
        e.printStackTrace();
    }

    Log.d(TAG, "Last Location: " + mLastLocation);

    latitude = mLastLocation.getLatitude();
    longitude = mLastLocation.getLongitude();
    Log.d(TAG, "Latitude: " + latitude + " Longitude: " + longitude);

    // Set title bar name to name of city
    Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
    try {
        List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) {
            cityName = addresses.get(0).getLocality();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Set title to city name
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(cityName);
    }

    getWeatherInfo(); // begin weather api
    modifyConfig(); // modify weather settings

    Log.d(TAG, "Last Location: " + mLastLocation);

}

From source file:dynamite.zafroshops.app.MainActivity.java

public LocationBase getAddress(boolean force) {
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    SharedPreferences preferences = getPreferences(0);
    SharedPreferences.Editor editor = preferences.edit();
    boolean locationToggle = preferences.getBoolean(StorageKeys.LOCATION_TOGGLE_KEY, locationToggleDefault);

    try {/*  w ww.j av a2s .c o  m*/
        if (!force && LastLocation != null) {

            if (preferences.contains(StorageKeys.COUNTRY_KEY)
                    && !preferences.getString(StorageKeys.COUNTRY_KEY, "").equals("")) {
                LastLocation.CountryCode = preferences.getString(StorageKeys.COUNTRY_KEY, "");
                LastLocation.Town = preferences.getString(StorageKeys.TOWN_KEY, "");
                LastLocation.Street = preferences.getString(StorageKeys.STREET_KEY, "");
                LastLocation.StreetNumber = preferences.getString(StorageKeys.STREETNUMBER_KEY, "");
            }
        } else if (locationToggle && LastLocation != null) {
            List<Address> addresses = geocoder.getFromLocation(LastLocation.Latitude, LastLocation.Longitude,
                    1);

            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);

                LastLocation.CountryCode = address.getCountryCode();
                LastLocation.Town = address.getLocality();

                if (address.getMaxAddressLineIndex() > 0) {
                    String line = address.getAddressLine(0);

                    if (line.compareTo(LastLocation.Town) < 0) {
                        LastLocation.Street = line.replaceAll("(\\D+) \\d+.*", "$1");
                        LastLocation.StreetNumber = line.replaceAll("\\D+ (\\d+.*)", "$1");
                    }
                }

                editor.putString(StorageKeys.COUNTRY_KEY, LastLocation.CountryCode);
                editor.putString(StorageKeys.TOWN_KEY, LastLocation.Town);
                editor.putString(StorageKeys.STREET_KEY, LastLocation.Street);
                editor.putString(StorageKeys.STREETNUMBER_KEY, LastLocation.StreetNumber);
                editor.commit();
            }
        } else {
            return null;
        }

        return LastLocation;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.taw.gotothere.GoToThereActivity.java

/**
 * Geocode the location the user typed into the search box, and centre the map
 * on it.//from w  ww.j a  v a2s .  c om
 */
private void geocodeResult(String address) {
    Log.d(TAG, "geocodeResult()");
    Geocoder geo = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geo.getFromLocationName(address, 10); // Hmmmm, 1?
        if (addresses.size() > 0) {
            GeoPoint pt = new GeoPoint((int) (addresses.get(0).getLatitude() * 1e6),
                    (int) (addresses.get(0).getLongitude() * 1e6));
            directionsImageView.setEnabled(true);
            navigationOverlay.setSelectedLocation(pt, this);
            map.getController().animateTo(pt);
            startMarkerPlacement();

            searchTextView.setText(address);
        } else {
            Toast.makeText(this, R.string.error_not_found_text, Toast.LENGTH_SHORT).show();
            searchTextView.setText(null);
        }
    } catch (IOException ioe) {
        Log.e(TAG, "Could not geocode '" + address + "'", ioe);
        Toast.makeText(this, R.string.error_general_text, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.TakeTaxi.jy.MainMapScreen.java

public void setGeoText() {

    geoadd = null;//from ww  w. j a va  2 s  . c  om
    Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
    try {
        List<Address> address = geocoder.getFromLocation(newLat / 1E6, newLongi / 1E6, 1);
        if (address.size() > 0) {
            geoadd = "";
            for (int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++) {
                if (i == 0) {
                    geoadd += address.get(0).getAddressLine(i);
                } else {
                    geoadd += "\n" + address.get(0).getAddressLine(i);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
    }
    tvCurrentGeocode = (TextView) findViewById(R.id.tvCurrentGeocode);

    tvCurrentGeocode.setText(geoadd);
}