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: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();
                        }//from w w w . j a va2s. c  o m
                    }
                } 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:com.android.jhansi.designchallenge.MapFragment.java

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
    try {//  ww  w.  ja v a2s.  co  m
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");

            strReturnedAddress.append(returnedAddress.getAddressLine(0)).append(" ");
            strReturnedAddress.append(returnedAddress.getLocality());
            strAdd = strReturnedAddress.toString();
            Log.w(TAG, "" + strReturnedAddress.toString());
        } else {
            Log.w(TAG, "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w(TAG, "Canont get Address!");
    }
    return strAdd;
}

From source file:com.qasp.diego.arsp.indice_localFrag.java

public String EncontraLocalizacao() {

    Geocoder geocoder;
    List<Address> addresses;
    geocoder = new Geocoder(getActivity(), Locale.getDefault());
    try {//from   w  ww . j av  a  2s  . c o m
        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.pk.ubulance.Activity.DisplayDriverActivity.java

public String getLocationName(Context mContext, Double latitude, Double longitude) {
    Geocoder myLocation = new Geocoder(mContext, Locale.getDefault());
    List<Address> myList = null;
    try {//w  w  w.j  av  a 2 s  . c om
        myList = myLocation.getFromLocation(latitude, longitude, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Address address = (Address) myList.get(0);
    String addressStr = "";
    addressStr += address.getAddressLine(0) + ", ";
    addressStr += address.getAddressLine(1) + ", ";
    addressStr += address.getAddressLine(2);
    Log.d("Ubulance", "Your Location: " + addressStr);
    return addressStr;
}

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;//  w  w  w .j  av a2s. co 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:eu.power_switch.gui.map.MapViewHandler.java

/**
 * Find a address description for a given coordinate
 *
 * @param latLng coordinate/*from  w  w  w .j  ava 2s. co  m*/
 * @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:com.kosratdahmad.location.MainActivity.java

@Override
public void onLocationChanged(Location location) {
    Log.i(TAG, "onLocationChanged: " + location.toString());

    String latitude = getString(R.string.latitude) + "    " + location.getLatitude();
    String longitude = getString(R.string.longitude) + "    " + location.getLongitude();

    mTextLatitude.setText(latitude);//  ww  w. jav  a 2s  . c  o m
    mTextLongitude.setText(longitude);

    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = null;
    try {
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        String cityName = getString(R.string.city) + "  " + addresses.get(0).getLocality();
        String stateName = getString(R.string.state) + "  " + addresses.get(0).getAdminArea();
        String countryName = getString(R.string.country) + "  " + addresses.get(0).getCountryName();

        mTextCity.setText(cityName);
        mTextState.setText(stateName);
        mTextCountry.setText(countryName);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.cianmcgovern.android.ShopAndShare.Share.java

/**
 * //  w ww .  j  a  v  a 2  s  .co  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.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 {//from   www  . ja v a  2 s  .  c  o  m
        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.jackpan.TaiwanpetadoptionApp.HeadpageActivity.java

@Override
public void onConnected(Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;/* w  ww . j  av  a2s . co m*/
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        Geocoder gc = new Geocoder(HeadpageActivity.this, Locale.TRADITIONAL_CHINESE);
        List<Address> lstAddress = null;
        try {
            lstAddress = gc.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
            String returnAddress = lstAddress.get(0).getAddressLine(0);
            Log.d(TAG, returnAddress);
            MyGAManager.setGaEvent(HeadpageActivity.this, "Location", "Location_now", returnAddress);
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        Log.d(TAG, "NO Location");
    }
}