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.cianmcgovern.android.ShopAndShare.Share.java

/**
 * /*  w  w w .  j  a  va  2  s  . c o m*/
 * Gets the address using the latitude and longitude from the getLocation()
 * 
 */
public void getAddress() {

    Geocoder geo = new Geocoder(this, Locale.ENGLISH);
    Address address = null;
    try {
        address = geo.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1).get(0);

        StringBuilder fullAddress = new StringBuilder();
        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            fullAddress.append(address.getAddressLine(i) + " ");
        }
        Log.v(Constants.LOG_TAG, "Got address: " + fullAddress.toString());

        mLocationEdit.setText(fullAddress.toString().trim());
    } catch (IOException e) {
        e.printStackTrace();
    }
    mSearch.setBackgroundResource(R.drawable.search);
}

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

public void onShow(View view) {
    LatLng lastKnownLatLng = null;/*from   ww  w. j av  a 2s  . co  m*/
    RealmResults<LocationPoint> result = mRealm.where(LocationPoint.class).findAll();
    for (LocationPoint point : result) {
        lastKnownLatLng = new LatLng(point.getLatitude(), point.getLongitude());
        addMarker(lastKnownLatLng, new SimpleDateFormat("dd/MM/yyyy hh:mm").format(point.getTimestamp()), "",
                0);
    }
    if (lastKnownLatLng != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(lastKnownLatLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
    }

    try {
        Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());

        List<Address> addressList = geocoder.getFromLocationName("Piata Unirii nr. 30, Cluj-Napoca", 1);
        LatLng eventLatLng = new LatLng(addressList.get(0).getLatitude(), addressList.get(0).getLongitude());

        addMarker(eventLatLng, "Dominic Miller (from Sting) and Miles Bould", "Muzeul de Arta",
                R.drawable.ic_action_maps_local_play);

        addressList = geocoder.getFromLocationName("Strada George Bariiu 26-28, Cluj-Napoca", 1);
        LatLng eventLatLng2 = new LatLng(addressList.get(0).getLatitude(), addressList.get(0).getLongitude());

        addMarker(eventLatLng2, "Facultatea de Automatica si Calculatoare", "",
                R.drawable.ic_action_maps_local_play);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.berniesanders.fieldthebern.controllers.LocationController.java

private Address getAddressForLocation(double lat, double lng) throws AddressUnavailableException {
    // Errors could still arise from using the Geocoder (for example, if there is no
    // connectivity, or if the Geocoder is given illegal location data). Or, the Geocoder may
    // simply not have an address for a location. In all these cases, we communicate with the
    // receiver using a resultCode indicating failure. If an address is found, we use a
    // resultCode indicating success.

    // The Geocoder used in this sample. The Geocoder's responses are localized for the given
    // Locale, which represents a specific geographical or linguistic region. Locales are used
    // to alter the presentation of information such as numbers or dates to suit the conventions
    // in the region they describe.
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    List<Address> addresses = null;
    Address address = null;/*from   www . j  a v a2s  .c  o m*/
    try {
        // Using getFromLocation() returns an array of Addresses for the area immediately
        // surrounding the given latitude and longitude. The results are a best guess and are
        // not guaranteed to be accurate.
        // In this sample, we get just a single address.
        addresses = geocoder.getFromLocation(lat, lng, 1);
    } catch (IOException | IllegalArgumentException ioException) {
        throw new AddressUnavailableException();
    }

    // Handle case where no address was found.
    if (addresses == null || addresses.size() == 0) {
        throw new AddressUnavailableException();
    } else {
        address = addresses.get(0);

        if (address == null || StringUtils.isBlank(address.getAdminArea())) {
            throw new AddressUnavailableException("address or state code was null/blank");
        }

        return address;
    }
}

From source file:net.palacesoft.cngstation.client.StationActivity.java

private Address lookupAddressFromLocationName(String city, String country)
        throws IOException, AddressEmptyException {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = Collections.emptyList();

    if (StringUtils.hasText(city)) {
        addresses = geocoder.getFromLocationName(city + " " + country, 1);
    }//from  w  ww  . j a  va2 s . c  o  m

    return extractAddress(addresses);
}

From source file:com.mobicage.rogerthat.GetLocationActivity.java

@Override
protected void onServiceBound() {
    T.UI();//w ww .j ava 2s.co m
    setContentView(R.layout.get_location);

    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    mProgressDialog.setMessage(getString(R.string.updating_location));
    mProgressDialog.setCancelable(true);
    mProgressDialog.setCanceledOnTouchOutside(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            T.UI();
            if (mLocationManager != null) {
                try {
                    mLocationManager.removeUpdates(mLocationListener);
                } catch (SecurityException e) {
                    L.bug(e); // Should never happen
                }
            }
        }
    });
    mProgressDialog.setMax(10000);

    mUseGPS = (CheckBox) findViewById(R.id.use_gps_provider);
    mGetCurrentLocationButton = (Button) findViewById(R.id.get_current_location);
    mAddress = (EditText) findViewById(R.id.address);
    mCalculate = (Button) findViewById(R.id.calculate);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (mLocationManager == null) {
        mGetCurrentLocationButton.setEnabled(false);
    } else {
        mUseGPS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked && !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    new AlertDialog.Builder(GetLocationActivity.this).setMessage(R.string.gps_is_not_enabled)
                            .setPositiveButton(R.string.yes, new SafeDialogInterfaceOnClickListener() {
                                @Override
                                public void safeOnClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivityForResult(intent, TURNING_ON_GPS);
                                }
                            }).setNegativeButton(R.string.no, new SafeDialogInterfaceOnClickListener() {
                                @Override
                                public void safeOnClick(DialogInterface dialog, int which) {
                                    mUseGPS.setChecked(false);
                                }
                            }).create().show();
                }
            }
        });

        mGetCurrentLocationButton.setOnClickListener(new SafeViewOnClickListener() {
            @Override
            public void safeOnClick(View v) {
                T.UI();
                if (mService.isPermitted(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    getMyLocation();
                } else {
                    ActivityCompat.requestPermissions(GetLocationActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                            PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
                }
            }
        });
    }

    mCalculate.setOnClickListener(new SafeViewOnClickListener() {
        @Override
        public void safeOnClick(View v) {
            final ProgressDialog pd = new ProgressDialog(GetLocationActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.setMessage(getString(R.string.updating_location));
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
            final String addressText = mAddress.getText().toString();
            mService.postOnIOHandler(new SafeRunnable() {
                @Override
                protected void safeRun() throws Exception {
                    Geocoder geoCoder = new Geocoder(GetLocationActivity.this, Locale.getDefault());
                    try {
                        List<Address> addresses = geoCoder.getFromLocationName(addressText, 5);
                        if (addresses.size() > 0) {
                            Address address = addresses.get(0);
                            final Location location = new Location("");
                            location.setLatitude(address.getLatitude());
                            location.setLongitude(address.getLongitude());
                            mService.postOnUIHandler(new SafeRunnable() {
                                @Override
                                protected void safeRun() throws Exception {
                                    pd.dismiss();
                                    mLocation = location;
                                    showMap();
                                }
                            });
                            return;
                        }
                    } catch (IOException e) {
                        L.d("Failed to geo code address " + addressText, e);
                    }
                    mService.postOnUIHandler(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            pd.dismiss();
                            UIUtils.showLongToast(GetLocationActivity.this,
                                    getString(R.string.failed_to_lookup_address));
                        }
                    });
                }
            });
        }
    });
}

From source file:com.ibm.mil.readyapps.telco.hotspots.HotSpotActivity.java

private void useOnlineMode(final Location userLocation) {
    final Geocoder geocoder = new Geocoder(this, Locale.getDefault());

    presenter.getOnlineHotSpots(geocoder, userLocation).compose(hotSpotTransformer()).subscribe(hotSpotOnNext(),
            new Action1<Throwable>() {
                @Override/*from  w  w w .j a v a  2 s . co m*/
                public void call(Throwable throwable) {
                    useOfflineMode(userLocation, geocoder);
                }
            });
}

From source file:eu.power_switch.gui.map.MapViewHandler.java

/**
 * Find a address description for a given coordinate
 *
 * @param latLng coordinate/*  www  .ja v a2s  . c  om*/
 * @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;
}

From source file:net.palacesoft.cngstation.client.StationActivity.java

private Address lookupAddressFromLocation(Location location) throws IOException, AddressEmptyException {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = Collections.emptyList();

    if (location != null) {
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
    }/*from w  w w. j  a v  a 2  s.co m*/

    return extractAddress(addresses);
}

From source file:com.example.android.uvdemo.MainActivity.java

private void getAddress(Double lat, Double lng) {
    Geocoder gc = new Geocoder(MainActivity.this, Locale.TRADITIONAL_CHINESE);
    List<Address> lstAddress;
    String countryname = "", adminarea = "", locality = "", postalcode = "";
    try {//  w  w w  . j  ava 2 s. c  om
        lstAddress = gc.getFromLocation(lat, lng, 1);
        countryname = lstAddress.get(0).getCountryName();
        adminarea = lstAddress.get(0).getAdminArea();// City
        locality = lstAddress.get(0).getLocality();// District
        postalcode = lstAddress.get(0).getPostalCode();
        Log.v(TAG, "=========================================");
        Log.v(TAG, "getAddress : " + "\nCountry : " + countryname + "\n City : " + adminarea + "\n District : "
                + locality + "\n PostalCode : " + postalcode + "\n LatLng : " + lat + " , " + lng);
        Log.v(TAG, "=========================================");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.waz.zclient.pages.main.conversation.LocationFragment.java

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (isGooglePlayServicesAvailable()) {
        googleApiClient = new GoogleApiClient.Builder(getContext()).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    } else {//from ww  w . j a v  a2 s. c  o  m
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    }
    mainHandler = new Handler();
    handlerThread = new HandlerThread("Background handler");
    handlerThread.start();
    backgroundHandler = new Handler(handlerThread.getLooper());
    geocoder = new Geocoder(getContext(), Locale.getDefault());
    zoom = true;
}