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.cloudbees.gasp.activity.GaspLocationsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_locations);

    GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    LocationManager locationManager;/*from  www.  j a  v a  2 s  .  c o m*/
    String svcName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(svcName);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);
    Log.i(TAG, "CURRENT LOCATION");
    Log.i(TAG, "Latitude = " + location.getLatitude());
    Log.i(TAG, "Longitude = " + location.getLongitude());

    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Geocoder gc = new Geocoder(this, Locale.getDefault());

        if (!Geocoder.isPresent())
            Log.i(TAG, "No geocoder available");
        else {
            try {
                List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0) {
                    Address address = addresses.get(0);

                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                        sb.append(address.getAddressLine(i)).append(" ");

                    sb.append(address.getLocality()).append("");
                    sb.append(address.getPostalCode()).append(" ");
                    sb.append(address.getCountryName());
                }
                Log.i(TAG, "Address: " + sb.toString());
            } catch (IOException e) {
                Log.d(TAG, "IOException getting address from geocoder", e);
            }
        }
    }

    map.setMyLocationEnabled(true);

    LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
    CameraPosition cameraPosition = new CameraPosition.Builder().target(myLocation).zoom(16).bearing(0).tilt(0)
            .build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    new LocationMapper().execute();
}

From source file:com.TomatoSauceStudio.OnTimeBirthdayPost.OnTimeBirthdayPost.java

/** Called when the activity is first created. */
@Override//from  w  ww  . j  a v a2 s. c o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /**
     * Request custom title-bar so we can display our own messages.
     */
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.main);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
    titleText = (TextView) findViewById(R.id.titlet);
    /**
     * Fix our orientation, the list looks best in Portrait and this way we
     * don't have to deal with orientation changes.
     */
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    /**
     * We will use this progress dialog throughout to display busy messages.
     */
    pdialog = new ProgressDialog(this);
    pdialog.setIndeterminate(true);
    /**
     * Init Facebook objects.
     */
    facebook = new Facebook(APP_SECRET);
    mAsyncRunner = new AsyncFacebookRunner(facebook);
    /**
     * Init DB.
     */
    mDbHelper = new BirthdaysDbAdapter(this);
    mDbHelper.open();
    /**
     * Init the geocoder that will help us map locations to longitude and thus approximate timezone.
     */
    geocoder = new Geocoder(this, Locale.getDefault());
    registerForContextMenu(getListView());
    /**
     * Get existing access_token if any and skip authorization if possible.
     */
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if (access_token != null) {
        facebook.setAccessToken(access_token);
    }
    if (expires != 0) {
        facebook.setAccessExpires(expires);
    }

    /**
     * Request FB auth again only if current session is invalid, else proceed to
     * request info from FB.
     */
    if (!facebook.isSessionValid()) {
        //Log.d("OnTimeBirthdayPost","Facebook session not valid. Redoing auth.");
        fbAuthWrapper();
    } else {
        //Log.d("OnTimeBirthdayPost","Facebook session valid. Proceeding to requests");
        makeFBRequests();
    }
}

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

private void logApps(List<String> newApps, List<String> currentApps) throws IOException {
    /*/*  w w  w.java  2s.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);
}

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

/**
 * Get location address from target location name.
 * <p/>//from w  w  w. ja v a2 s .co  m
 * Use Android Geocode class.
 * <p/>
 *
 * @param context Context.
 * @param locale  Locale.
 * @param name    Location name.
 * @return Location address.
 */
@Deprecated
public static LatLng nameToPoint(final Context context, final Locale locale, final String name) {
    LatLng address = null;

    try {
        Geocoder geocoder = new Geocoder(context, locale);
        List<Address> addressList = null;

        try {
            addressList = geocoder.getFromLocationName(name, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if ((addressList != null) && !addressList.isEmpty()) {
            for (Address point : addressList) {
                double latitude = point.getLatitude();
                double longitude = point.getLongitude();
                address = new LatLng(latitude, longitude);
            }
        }

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

    return address;
}

From source file:com.binomed.showtime.android.util.CineShowtimeFactory.java

public static void initGeocoder(Context context) {
    CineShowtimeFactory.getInstance().setGeocoder(new Geocoder(context, Locale.getDefault()));
}

From source file:com.example.aula20141117.util.AmUtil.java

public LatLng getLatLongFromString(String address, Activity calling) {
    LatLng ret = null;/*from w ww  . j  a  v a2 s  . co  m*/

    double lat = 0.0, lng = 0.0;

    Geocoder geoCoder = new Geocoder(calling, Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocationName(address, 1);
        if (addresses.size() > 0) {
            GeoPoint p = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6),
                    (int) (addresses.get(0).getLongitude() * 1E6));

            lat = p.getLatitudeE6() / 1E6;
            lng = p.getLongitudeE6() / 1E6;

            Log.d("Latitude", "" + lat);
            Log.d("Longitude", "" + lng);

            ret = new LatLng(lat, lng);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return ret;
}

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 {/*from   w w w .  j  a  va2s. 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:com.qasp.diego.arsp.indice_localFrag.java

public String EncontraLocalizacao() {

    Geocoder geocoder;//from w  w  w .ja  va2  s.  com
    List<Address> addresses;
    geocoder = new Geocoder(getActivity(), Locale.getDefault());
    try {
        addresses = geocoder.getFromLocation(Global.GPS.getLatitude(), Global.GPS.getLongitude(), 1);
        try {
            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
            String city = addresses.get(0).getLocality();
            Global.endereco = "Endereo: " + address + " - " + city;
        } catch (IndexOutOfBoundsException e) {
            if (Global.endereco.equals(" "))
                return ("Endereo: Falha em obter o endereo do local");
        }
    } catch (IOException e) {
        if (Global.endereco.equals(" "))
            return ("Endereo: Falha em obter o endereo do local");
    }
    return Global.endereco;
}

From source file:com.sahana.geosmser.view.ReverseGeocoderView.java

public GeoPoint getGeoByDefaultAddress(String searchAddress) {
    GeoPoint mGeoPoint = null;// ww  w. j a  v a2s . c  o m
    try {
        if (!searchAddress.equals("")) {
            Geocoder mGeocoder = new Geocoder(mContext, Locale.getDefault());
            List<Address> mAddressList = mGeocoder.getFromLocationName(searchAddress, 1);
            if (!mAddressList.isEmpty()) {
                Address mAddress = mAddressList.get(0);
                double mLatitude = mAddress.getLatitude() * 1E6;
                double mLongitude = mAddress.getLongitude() * 1E6;
                mGeoPoint = new GeoPoint((int) mLatitude, (int) mLongitude);
            } else {
                Log.d(WhereToMeet.TAG, "Address Not Found!");
            }
        }
    } catch (Exception e) {
        Log.d(com.sahana.geosmser.WhereToMeet.TAG, e.getMessage());
    }
    return mGeoPoint;
}

From source file:com.cmput301w17t07.moody.EditMoodActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    UserController userController = new UserController();
    userName = userController.readUsername(EditMoodActivity.this).toString();
    setContentView(R.layout.activity_edit_mood);
    setUpMenuBar(this);

    // get the mood object that was selected
    Intent intent = getIntent();/*  w w w  .j av a 2  s.  c  om*/
    editMood = (Mood) intent.getSerializableExtra("editMood");
    date = editMood.getDate();
    bitmapImage = (Bitmap) intent.getParcelableExtra("bitmapback");
    editBitmapImage = bitmapImage;
    deletedPic = (int) intent.getExtras().getInt("bitmapdelete");
    latitude = editMood.getLatitude();
    longitude = editMood.getLongitude();
    image = (ImageView) findViewById(R.id.editImageView);
    final TextView location = (TextView) findViewById(R.id.locationText);
    address = editMood.getDisplayLocation();
    location.setText(address);

    if (latitude == 0 && longitude == 0) {
        location1 = null;
    }
    displayAttributes();
    if (deletedPic == 1) {
        image.setImageBitmap(null);
    }

    //set up the button and imageButton
    ImageButton editLocation = (ImageButton) findViewById(R.id.location);
    editLocation.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            locationText = (TextView) findViewById(R.id.locationText);
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            //check available tools
            List<String> locationList = locationManager.getProviders(true);
            if (locationList.contains(LocationManager.GPS_PROVIDER)) {
                provider = LocationManager.GPS_PROVIDER;
            } else if (locationList.contains(LocationManager.NETWORK_PROVIDER)) {
                provider = LocationManager.NETWORK_PROVIDER;
            } else {
                Toast.makeText(getApplicationContext(), "Please check your permissions", Toast.LENGTH_LONG)
                        .show();
            }
            //check the permission
            if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getApplicationContext(),
                            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                Toast.makeText(getApplicationContext(),
                        "Getting location failed, Please check the application permissions", Toast.LENGTH_SHORT)
                        .show();
                return;
            }

            location1 = locationManager.getLastKnownLocation(provider);
            if (location1 == null) {
                latitude = 0;
                longitude = 0;
            } else {
                latitude = location1.getLatitude();
                longitude = location1.getLongitude();
            }

            //get the location name by latitude and longitude
            Geocoder gcd = new Geocoder(EditMoodActivity.this, Locale.getDefault());
            try {
                List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);

                if (addresses.size() > 0)
                    address = "  " + addresses.get(0).getFeatureName() + " "
                            + addresses.get(0).getThoroughfare() + ", " + addresses.get(0).getLocality() + ", "
                            + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryCode();
                location.setText(address);
            } catch (Exception e) {
                e.printStackTrace();
            }

            final ImageButton deleteLocation = (ImageButton) findViewById(R.id.deleteLocation);
            deleteLocation.setVisibility(View.VISIBLE);
            deleteLocation.setEnabled(true);
        }
    });

    editLocation.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            moodMessage_text = Description.getText().toString();
            editMood.setMoodMessage(moodMessage_text);
            editMood.setDate(date);
            Intent editLocation = new Intent(EditMoodActivity.this, EditLocation.class);
            editLocation.putExtra("EditMood", editMood);
            editLocation.putExtra("bitmap", compress(editBitmapImage));
            startActivity(editLocation);
            return true;
        }
    });

    final ImageButton deleteLocation = (ImageButton) findViewById(R.id.deleteLocation);
    deleteLocation.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            location1 = null;
            locationText = (TextView) findViewById(R.id.locationText);
            address = null;
            locationText.setText(address);
            latitude = 0;
            longitude = 0;
            deleteLocation.setVisibility(View.INVISIBLE);
            deleteLocation.setEnabled(false);
        }
    });

    ImageButton editCameraButton = (ImageButton) findViewById(R.id.editCamera);
    editCameraButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, 1);
            } catch (Exception e) {
                Intent intent = new Intent(getApplicationContext(), EditMoodActivity.class);
                startActivity(intent);
            }
        }
    });

    editCameraButton.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            try {
                Intent intent = new Intent("android.intent.action.PICK");
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            } catch (Exception e) {
                Intent intent = new Intent(getApplicationContext(), EditMoodActivity.class);
                startActivity(intent);
            }
            return true;
        }
    });

    ImageButton PickerButton = (ImageButton) findViewById(R.id.EditDate);
    PickerButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            innit();
            TimeDialog.show();
        }
    });
    Button submitButton = (Button) findViewById(R.id.button5);
    submitButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            moodMessage_text = Description.getText().toString();
            MoodController moodController = new MoodController();
            editBitmapImage = bitmapImage;
            AchievementManager.initManager(EditMoodActivity.this);
            AchievementController achievementController = new AchievementController();
            achievements = achievementController.getAchievements();
            achievements.firstTimeEditFlag = 1;
            achievementController.saveAchievements();

            if (!moodController.editMood(EmotionText, userName, moodMessage_text, latitude, longitude,
                    editBitmapImage, SocialSituation, date, address, editMood, EditMoodActivity.this)) {
                Toast.makeText(EditMoodActivity.this, "Mood message length is too long. Please try again",
                        Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(EditMoodActivity.this, TimelineActivity.class);
                startActivity(intent);
                finish();
            }
        }
    });

    // TODO button needs only display when image present in Mood
    final ImageButton deletePicture = (ImageButton) findViewById(R.id.deletePicture);
    if (editBitmapImage == null || deletedPic == 1) {
        deletePicture.setVisibility(View.INVISIBLE);
        deletePicture.setEnabled(false);
    }
    deletePicture.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            bitmapImage = null;
            editBitmapImage = null;
            image.setImageDrawable(null);
            deletePicture.setVisibility(View.INVISIBLE);
            deletePicture.setEnabled(false);
        }
    });
}