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) 

Source Link

Document

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

Usage

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

/**
 * Callback called when connected to GCore. Implementation of {@link com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks}.
 *//* w  w w.  j  a va2  s .co 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:edu.usf.cutr.opentripplanner.android.tasks.OTPGeocoding.java

protected Long doInBackground(String... reqs) {
    long count = reqs.length;

    String address = reqs[0];//w  ww .  j a va  2 s  .co m
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    if (address == null || address.equalsIgnoreCase("")) {
        return count;
    }

    if (address.equalsIgnoreCase(context.getString(R.string.my_location))) {
        String currentLat = reqs[1];
        String currentLng = reqs[2];
        LatLng latLng = new LatLng(Double.parseDouble(currentLat), Double.parseDouble(currentLng));

        Address addressReturn = new Address(context.getResources().getConfiguration().locale);
        addressReturn.setLatitude(latLng.latitude);
        addressReturn.setLongitude(latLng.longitude);
        addressReturn.setAddressLine(addressReturn.getMaxAddressLineIndex() + 1,
                context.getString(R.string.my_location));

        addressesReturn.add(addressReturn);

        return count;
    }

    ArrayList<Address> addresses = null;

    if (prefs.getBoolean(OTPApp.PREFERENCE_KEY_USE_ANDROID_GEOCODER, true)) {
        Log.d("test", "create a geocoder");
        Geocoder gc = new Geocoder(context);
        try {
            if (selectedServer != null) {
                addresses = (ArrayList<Address>) gc.getFromLocationName(address,
                        context.getResources().getInteger(R.integer.geocoder_max_results),
                        selectedServer.getLowerLeftLatitude(), selectedServer.getLowerLeftLongitude(),
                        selectedServer.getUpperRightLatitude(), selectedServer.getUpperRightLongitude());
            } else {
                addresses = (ArrayList<Address>) gc.getFromLocationName(address,
                        context.getResources().getInteger(R.integer.geocoder_max_results));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    addresses = filterAddressesBBox(addresses);

    if ((addresses == null) || addresses.isEmpty()) {
        addresses = searchPlaces(address);

        for (int i = 0; i < addresses.size(); i++) {
            Address addr = addresses.get(i);
            String str = addr.getAddressLine(0);
            List<String> addrLines = Arrays.asList(str.split(", "));
            for (int j = 0; j < addrLines.size(); j++) {
                addr.setAddressLine(j, addrLines.get(j));
            }
        }
    }

    addresses = filterAddressesBBox(addresses);

    addressesReturn.addAll(addresses);

    return count;
}

From source file:net.sylvek.sharemyposition.ShareMyPosition.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    HttpProtocolParams.setUserAgent(params, "Android/" + Build.DISPLAY + "/version:" + VERSION);

    gc = new Geocoder(this);

    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    pref = PreferenceManager.getDefaultSharedPreferences(this);

    tips = getResources().getStringArray(R.array.tips);

    sharedMap = new MapView(ShareMyPosition.this, MapViewMode.MAPNIK_TILE_DOWNLOAD);
    sharedMap.setClickable(true);/*from  w w w.  j a va 2s.  c  o  m*/
    sharedMap.setAlwaysDrawnWithCacheEnabled(true);
    sharedMap.setFocusable(true);
    sharedMap.getOverlays().add(new CenterOverlay(sharedMap));
}

From source file:de.j4velin.wifiAutoOff.Locations.java

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (requestCode == REQUEST_LOCATION) {
        if (resultCode == RESULT_OK) {
            LatLng location = data.getParcelableExtra("location");
            String locationName = "UNKNOWN";
            if (Geocoder.isPresent()) {
                Geocoder gc = new Geocoder(this);
                try {
                    List<Address> result = gc.getFromLocation(location.latitude, location.longitude, 1);
                    if (result != null && !result.isEmpty()) {
                        Address address = result.get(0);
                        locationName = address.getAddressLine(0);
                        if (address.getLocality() != null) {
                            locationName += ", " + address.getLocality();
                        }/* w  w w  . j  a  v  a  2 s  . c om*/
                    }
                } catch (IOException e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    e.printStackTrace();
                }
            }
            Database db = Database.getInstance(this);
            db.addLocation(locationName, location);
            db.close();
            locations.add(new Location(locationName, location));
            mAdapter.notifyDataSetChanged();
        }
    } else if (requestCode == REQUEST_BUY) {
        if (resultCode == RESULT_OK) {
            if (data.getIntExtra("RESPONSE_CODE", 0) == 0) {
                try {
                    JSONObject jo = new JSONObject(data.getStringExtra("INAPP_PURCHASE_DATA"));
                    PREMIUM_ENABLED = jo.getString("productId").equals("de.j4velin.wifiautomatic.billing.pro")
                            && jo.getString("developerPayload").equals(getPackageName());
                    getSharedPreferences("settings", Context.MODE_PRIVATE).edit()
                            .putBoolean("pro", PREMIUM_ENABLED).commit();
                    if (PREMIUM_ENABLED) {
                        Toast.makeText(this, "Thank you!", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    Toast.makeText(this, e.getClass().getName() + ": " + e.getMessage(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

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();/*from w  ww.  j av  a2s  . c  om*/
    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:com.geoffreybuttercrumbs.arewethereyet.ZonePicker.java

private void saveAlarmPoint() {
    Location location = zone.getLocation();
    if (location == null) {
        Toast.makeText(this, "No location. Try again...", Toast.LENGTH_LONG).show();
        return;//from  ww w  .  j av a 2  s  .c  o  m
    }

    Geocoder geocoder = new Geocoder(this);
    List<Address> addresses;
    String address;
    try {
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        address = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getLocality();
    } catch (IOException e) {
        //         Log.e("Geoffrey", "Geocoding error...");
        e.printStackTrace();
        address = "Unknown address";
    }

    saveCoordinatesInPreferences((float) location.getLatitude(), (float) location.getLongitude(),
            zone.getRadius(), address);
    locationManager.removeUpdates(this);

    Intent bdintent = new Intent();
    bdintent.setClassName("com.geoffreybuttercrumbs.arewethereyet",
            "com.geoffreybuttercrumbs.arewethereyet.AlarmService");
    bdintent.putExtra(RADIUS, zone.getRadius());
    bdintent.putExtra(LOC, location);
    bdintent.putExtra(TONE, uri);
    bdintent.putExtra(ADDRESS, address);
    startService(bdintent);

    Toast.makeText(this, "Saving Alarm...", Toast.LENGTH_LONG).show();

    finish();
}

From source file:fr.gotorennes.AbstractMapActivity.java

public static Location getLocation(Context context, String address) {
    if ("".equals(address.trim())) {
        android.location.Location l = LocationUtils.getLocation(context);
        return l != null
                ? new Location(l.getLatitude(), l.getLongitude(), context.getString(R.string.positionActuelle))
                : null;//  w w  w .jav  a 2s  .co m
    }

    Geocoder geocoder = new Geocoder(context);
    try {
        List<Address> addresses = geocoder.getFromLocationName(address + ",35 ille et vilaine", 1);
        if (addresses != null && !addresses.isEmpty()) {
            Address foundAddress = addresses.get(0);
            return new Location(foundAddress.getLatitude(), foundAddress.getLongitude(),
                    foundAddress.getAddressLine(0));
        }
    } catch (Exception ex) {
        Log.e("GoToRennes", ex.getMessage());
    }
    return null;
}

From source file:com.timemachine.controller.ControllerActivity.java

private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String input = intent.getStringExtra(SearchManager.QUERY);
        String suggestion = (String) intent.getExtras().get("intent_extra_data_key");
        String query;/*from   w w  w. j  av a2  s .  c  om*/
        // Use the query to search your data somehow
        if (suggestion == null)
            query = input;
        else
            query = suggestion;
        Geocoder geocoder = new Geocoder(ControllerActivity.this);
        try {
            List<Address> address = geocoder.getFromLocationName(query, 1);
            if (address != null && !address.isEmpty()) {
                Address location = address.get(0);
                System.out.println(location.getLatitude() + ", " + location.getLongitude());
                mMap.animateCamera(
                        CameraUpdateFactory.newLatLngZoom(
                                new LatLng(location.getLatitude(), location.getLongitude()), maxZoom),
                        animateCameraDuration, null);
            } else
                System.out.println("No address found.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.ant.sunshine.app.activities.MainActivity.java

private void reloadLocationIfChanged(String location) {
    if (location != null && !location.equals(mLocation)) {
        Fragment fragment = getFragmentById();
        if (isForecastFragment(fragment)) {
            reloadLocation();/*w  w  w. j  a  v  a  2s  . co m*/
            updateLocationForecast(location);
        } else {
            MapLocationFragment mapLocationFragment = (MapLocationFragment) fragment;
            if (mapLocationFragment != null) {
                try {
                    Geocoder geocoder = new Geocoder(this);
                    List<Address> addressList = geocoder.getFromLocationName(location, 1);
                    Address address = addressList.get(0);
                    Location loc = new Location("");
                    loc.setLatitude(address.getLatitude());
                    loc.setLongitude(address.getLongitude());
                    mapLocationFragment.getLocationListener().onLocationChanged(loc);
                } catch (IOException ioex) {
                    Toast.makeText(this, "Exception in loading the address!", Toast.LENGTH_SHORT).show();
                } catch (Exception exc) {
                    Toast.makeText(this, "Exception in loading the address!", Toast.LENGTH_SHORT).show();
                }
            }
        }

        mLocation = location;
    }
}

From source file:com.ratebeer.android.gui.fragments.BrewerViewFragment.java

private void setDetails() {
    nameText.setText(brewer.brewerName);
    descriptionText.setText(brewer.description == null ? "" : brewer.description);
    String state = "";
    String country = "";
    if (brewer.countryID > 0 && Country.ALL_COUNTRIES.containsKey(brewer.countryID)) {
        country = "\n" + Country.ALL_COUNTRIES.get(brewer.countryID).getName();
        if (brewer.stateID > 0 && State.ALL_STATES.containsKey(brewer.countryID)) {
            Map<Integer, State> states = State.ALL_STATES.get(brewer.countryID);
            if (states.containsKey(brewer.stateID)) {
                state = ", " + states.get(brewer.stateID).getName();
            }// w w  w  . j  ava 2  s  .c om
        }
    }
    locationText.setText(brewer.address + "\n" + brewer.city + state + country);
    websiteButton.setText(brewer.website);
    //facebookButton.setText(brewer.facebook); // Just use the text 'Facebook', because often this isn't a nice looking name
    twitterButton.setText("@" + brewer.twitter);

    // Make fields visible too
    descriptionText.setVisibility(
            brewer.description.equals("") || brewer.description.equals("null") ? View.GONE : View.VISIBLE);
    locationText.setVisibility(View.VISIBLE);
    websiteButton.setVisibility(
            brewer.website.equals("") || brewer.website.equals("null") ? View.GONE : View.VISIBLE);
    facebookButton.setVisibility(
            brewer.facebook.equals("") || brewer.facebook.equals("null") ? View.GONE : View.VISIBLE);
    twitterButton.setVisibility(
            brewer.twitter.equals("") || brewer.twitter.equals("null") ? View.GONE : View.VISIBLE);

    if (getMap() != null) {
        try {
            // Use Geocoder to look up the coordinates of this brewer
            try {
                List<Address> point = new Geocoder(getActivity())
                        .getFromLocationName(brewer.address + " " + brewer.city, 1);
                if (point.size() <= 0) {
                    // Cannot find address: hide the map
                    getMapView().setVisibility(View.GONE);
                } else {
                    // Found a location! Center the map here
                    LocationUtils.initGoogleMap(getMap(), point.get(0).getLatitude(),
                            point.get(0).getLongitude());
                    getMap().addMarker(new MarkerOptions()
                            .position(new LatLng(point.get(0).getLatitude(), point.get(0).getLongitude()))
                            .title(brewer.brewerName).snippet(brewer.city)
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
                    getMapView().setVisibility(View.VISIBLE);
                }
            } catch (IOException e) {
                // Can't connect to Geocoder server: hide the map
                getMapView().setVisibility(View.GONE);
            }
        } catch (NoSuchMethodError e) {
            // Geocoder is not available at all: hide the map
            getMapView().setVisibility(View.GONE);
        }
    }

}