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:eu.power_switch.gui.map.MapViewHandler.java

/**
 * Find Coordinates for a given address//from   w  w  w.j av a 2 s . co m
 *
 * @param address address as text
 * @return coordinate near the given address
 * @throws AddressNotFoundException
 */
public LatLng findCoordinates(String address) throws CoordinatesNotFoundException {
    /* get latitude and longitude from the address */
    Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocationName(address, 5);
        if (addresses.size() > 0) {
            Double lat = (addresses.get(0).getLatitude());
            Double lon = (addresses.get(0).getLongitude());

            Log.d("lat-lon", lat + "......." + lon);
            final LatLng location = new LatLng(lat, lon);
            return location;
        } else {
            throw new CoordinatesNotFoundException(address);
        }
    } catch (IOException e) {
        Log.e(e);
    }

    return null;
}

From source file:com.capstone.transit.trans_it.TripDisplayActivity.java

public double[] getFromLocation(String address) {

    double[] Coordinates = new double[2];

    Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
    try {//from   ww w.ja  va  2s.  c  o  m
        Address addressConvert = geoCoder.getFromLocationName(address, 1).get(0);
        Coordinates[0] = addressConvert.getLatitude();
        Coordinates[1] = addressConvert.getLongitude();

    } catch (Exception ee) {

    }

    return Coordinates;
}

From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getCurrentGPSLocationBroadcastReceiver = new BroadcastReceiver() {
        @Override/*from   ww  w.  j  a v  a2s. c o m*/
        public void onReceive(Context context, Intent intent) {

            //  if(!test) {
            // textView.append("\n" +intent.getExtras().get("coordinates"));
            if (intent.getExtras().containsKey("longitude")) {
                double longitude = (double) intent.getExtras().get("longitude");
                double latitude = (double) intent.getExtras().get("latitude");
                googleMap.clear();
                setMapView(longitude, latitude);

                Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
                try {
                    List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }

                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());

                        result.setLatitude(latitude);
                        result.setLongitude(longitude);

                        result.setCountryName(address.getCountryName());
                        result.setLocality(address.getLocality());
                        result.setZipCode(address.getPostalCode());

                        result.setLocation(sb.toString());

                        if (address.getCountryCode().equals("TW")) {
                            result.setAddress(
                                    address.getAddressLine(0).substring(3, address.getAddressLine(0).length()));
                            result.setLocation(
                                    address.getAddressLine(0).substring(3, address.getAddressLine(0).length()));
                        } else {
                            result.setAddress(sb.toString());
                            result.setLocation(sb.toString());

                        }
                    }
                } catch (IOException e) {
                    Log.e("", "Unable connect to Geocoder", e);
                }
                //test = true;
            }
            // }
        }
    };

    sendDataRequest = new JsonPutsUtil(getActivity());
    sendDataRequest.setServerRequestOrderManagerCallBackFunction(
            new JsonPutsUtil.ServerRequestOrderManagerCallBackFunction() {

                @Override
                public void createNormalOrder(NormalOrder order) {

                    if (progressDialog_loading != null) {
                        progressDialog_loading.cancel();
                        progressDialog_loading = null;
                    }
                    Intent intent = new Intent(getActivity(), ClientTakeRideSearchActivity.class);

                    Bundle b = new Bundle();
                    b.putInt(Constants.ARG_POSITION, Integer.valueOf(order.getTicket_id()));
                    intent.putExtras(b);
                    startActivity(intent);
                    //finish();
                }

                @Override
                public void cancelNormalOrder(NormalOrder order) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                    //finish();
                }
            });
}

From source file:com.ashok.location_basicexamplefromgoogle.MainActivity.java

/** ---------------------------------------------------
 * Display Latitute, Longitude and City name using Reverse-GeoCoding
 */// w  w w  . jav a2  s .  co m
protected void displayLatLong_and_streetAddr(Location mLastLocation) {
    Double latitude, longitude;
    String addressLine = "addressLine";
    String cityAndState = "City&stateName";
    String countryName = "CountryName";
    latitude = mLastLocation.getLatitude();
    longitude = mLastLocation.getLongitude();

    //Get City, State anc Country name by using Reverse-Geocoding
    Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
    try {//Reverse GeoCoding - Get street-address from Latitude, Longitude
        List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
        addressLine = address.get(0).getAddressLine(0);
        cityAndState = address.get(0).getAddressLine(1);
        countryName = address.get(0).getAddressLine(2);
    } catch (IOException ioe) {
        Log.i(TAG, "Error:ReverseGeoCoding:NetworkNotAvailable:display_lat_lng_cityName()");
        mTxtError.setText("Error:ReverseGeoCoding:IOException.NetworkNotAvailable.display_lat_lng_cityName()");
        ioe.printStackTrace();
    } catch (IllegalArgumentException iae) {
        Log.i(TAG, "Error:ReverseGeoCoding:IllegalArgs:display_lat_lng_cityName()");
        mTxtError.setText("Error:ReverseGeoCoding:IllegalArgs:display_lat_lng_cityName()");
        iae.printStackTrace();
    }
    mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel, latitude));
    mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel, longitude));
    mTxtAddressLine.setText(addressLine);
    mTxtCityAndState.setText(cityAndState);
    mTxtCountryName.setText(countryName);
}

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

private void setupEventData(Event event) {
    if (user == null || mEvent.getUserId() == user.getId()) {
        eventDetailJoinBtn.setVisibility(View.GONE);
    } else {/*from ww  w .ja va 2s  . co m*/
        int visibility = View.VISIBLE;
        for (User usr : event.getUsers()) {
            if (usr.getId() == user.getId()) {
                visibility = View.GONE;
                break;
            }
        }

        eventDetailJoinBtn.setVisibility(visibility);
    }

    eventDetailName.setText(event.getName());
    if (event.getStart() != null)
        eventDetailTime.setText(String.format("%s, %s", DateTimeUtils.DATE_TIME_FORMAT.format(event.getStart()),
                DateTimeUtils.getDurationTimeString(getContext(), event.getDuration() * 60 * 1000)));
    else
        eventDetailTime.setText("?");
    eventDetailDescription.setText(event.getDescription());

    eventDetailPhone.setText(event.getContact().getPhone());
    eventDetailEmail.setText(event.getContact().getEmail());

    eventDetailWeHave.setText(event.getHave());
    eventDetailBring.setText(event.getBring());

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

    eventDetailPosition.setText(
            PositionUtils.getFormattedLocation(getContext(), event.getGps().getLat(), event.getGps().getLng()));

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

    if (event.getTrashPoints() != null && !event.getTrashPoints().isEmpty()) {
        eventDetailListOfTrashTitle.setVisibility(View.VISIBLE);
        eventDetailTrashlispCardView.setVisibility(View.VISIBLE);

        eventDetailTrashListContainer.removeAllViews();
        for (TrashPoint trashPoint : event.getTrashPoints()) {
            if (eventDetailTrashListContainer.getChildCount() > 0)
                eventDetailTrashListContainer.addView(ViewUtils.getDividerView(getContext()));

            eventDetailTrashListContainer.addView(getTrashView(trashPoint));
        }
    } else {
        eventDetailListOfTrashTitle.setVisibility(View.GONE);
        eventDetailTrashlispCardView.setVisibility(View.GONE);
    }
}

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 {//from   w ww . j a  va2 s.  c o 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.hangulo.powercontact.MainActivity.java

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

    // supprot two pane mode
    mTwoPane = getResources().getBoolean(R.bool.two_pane); // two_pane mode check

    // Analytics tracking start
    ((AnalyticsApplication) getApplication()).startTracking();

    // use toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
    setSupportActionBar(toolbar); // ?  

    // setting left drawer
    setleftMenuDrawer(toolbar);//from w ww  . j a v  a2s  . c  o m

    mTopFrameLayout = (FrameLayout) findViewById(R.id.top_frame_layout); //   ?
    mTopLayout = (android.support.design.widget.AppBarLayout) findViewById(R.id.layout_toolbar); //  ?? ?
    mProgressCircle = (ProgressBar) findViewById(R.id.loading_circle); // loading circle

    //  ?? ?  ?? . (? ? .)
    mGeocoder = new Geocoder(this, Locale.KOREA); //  public Geocoder (Context context, Locale locale) // why korea??? -=--> ? ?. ? ??.

    mTextDemoMode = (TextView) findViewById(R.id.text_demo_mode);
    mMakeDemoButton = (FloatingActionButton) findViewById(R.id.fab_make_demo);
    mMakeDemoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            makeDemoData(200);
            getSupportLoaderManager().restartLoader(Constants.POWERCONTACT_LOADER, null, MainActivity.this); // reset Loader

        }
    });

    readDefaultSettings(mPowerContactSettings); //  ? ?. (? ??  .)

    if (savedInstanceState != null) { // ? ? ? ....
        // If we're restoring state after this fragment was recreated then
        // retrieve previous search term and previously selected search
        // result.

        mSearchKeyword = savedInstanceState.getString(QUERY_KEY);
        mPreviousSearchKeyword = mSearchKeyword; // ?
        mPowerContactSettings = savedInstanceState.getParcelable(POWER_CONTACT_SETTINGS_KEY);
        demoCreated = savedInstanceState.getBoolean(DEMO_CREATED_KEY);

        // https://developers.google.com/android/guides/api-client
        mResolvingError = savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
        mIsExpandedFragment = savedInstanceState.getBoolean("IS_EXPANDED", false); //  ? ? ?
        // Update the value of mCurrentLocation from the Bundle and update the UI to show the
        // correct latitude and longitude.
        if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
            // Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
            // is not null.
            mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
        }

        // Update the value of mLastUpdateTime from the Bundle and update the UI.
        if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
            mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
        }
    }

    Intent intent = getIntent();

    if (intent != null) {
        FROM_WIDGET = intent.getBooleanExtra(Constants.FROM_WIDGET_KEY, false);

        if (FROM_WIDGET) {
            Log.v(LOG_TAG, "From Widget distance");
            setDistance(0.0f); // distance all
            mPowerContactSettings.setDemoMode(false);
        }

    }
    //  ? ??

    toggleDemoMode(mPowerContactSettings.isDemoMode()); // demo mode false!

    buildGoogleApiClient(); //   

    // https://github.com/umano/AndroidSlidingUpPanel/blob/master/demo/src/com/sothree/slidinguppanel/demo/DemoActivity.java
    mMapFragment = (MapViewFragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT_PANE1);
    mListFragment = (ContactsListFragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT_PANE2);
    if (mMapFragment == null)
        mMapFragment = new MapViewFragment();

    if (mListFragment == null)
        mListFragment = new ContactsListFragment();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.contact_map_view_container, mMapFragment, TAG_FRAGMENT_PANE1).commit();
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.contact_list_view_container, mListFragment, TAG_FRAGMENT_PANE2).commit();

}

From source file:org.jraf.android.piclabel.app.form.FormActivity.java

private String reverseGeocode(float lat, float lon) {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses;
    try {//  www.  j av  a 2 s  .  c  o m
        addresses = geocoder.getFromLocation(lat, lon, 1);
    } catch (Throwable t) {
        Log.w(TAG, "reverseGeocode Could not reverse geocode", t);
        return null;
    }
    if (addresses == null || addresses.isEmpty())
        return null;
    Address address = addresses.get(0);
    ArrayList<String> strings = new ArrayList<String>(5);
    if (address.getMaxAddressLineIndex() > 0)
        strings.add(address.getAddressLine(0));
    if (!TextUtils.isEmpty(address.getLocality()))
        strings.add(address.getLocality());
    if (!TextUtils.isEmpty(address.getCountryName()))
        strings.add(address.getCountryName());
    return TextUtils.join(", ", strings);
}

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);/*from  www . j a  v a 2  s .co  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.google.android.gms.location.sample.geofencing.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    startService(new Intent(this, GsmService.class));
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    GeoFenceApp.getLocationUtilityInstance().initialize(this);
    dataSource = GeoFenceApp.getInstance().getDataSource();
    TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String networkOperator = tel.getNetworkOperator();
    int mcc = 0, mnc = 0;
    if (networkOperator != null) {
        mcc = Integer.parseInt(networkOperator.substring(0, 3));
        mnc = Integer.parseInt(networkOperator.substring(3));
    }//from  w  ww.j ava  2 s . co  m
    Log.i("", "mcc:" + mcc);
    Log.i("", "mnc:" + mnc);
    final AutoCompleteTextView autocompleteView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    mAdapter = new PlacesAutoCompleteAdapter(this, R.layout.text_adapter);
    autocompleteView.setAdapter(mAdapter);
    autocompleteView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Get data associated with the specified position
            // in the list (AdapterView)
            String description = (String) parent.getItemAtPosition(position);
            place = description;
            Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show();
            try {
                Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocationName(description, 1);
                Address address = addresses.get(0);
                if (addresses.size() > 0) {
                    autocompleteView.clearFocus();
                    //inputManager.hideSoftInputFromWindow(autocompleteView.getWindowToken(), 0);
                    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                    Location location = new Location("Searched_Location");
                    location.setLatitude(latLng.latitude);
                    location.setLongitude(latLng.longitude);
                    setupMApIfNeeded(latLng);
                    //setUpMapIfNeeded(location);
                    //searchBar.setVisibility(View.GONE);
                    //searchBtn.setVisibility(View.VISIBLE);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    // Get the UI widgets.
    mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
    mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button);

    // Empty list for storing geofences.
    mGeofenceList = new ArrayList<Geofence>();

    // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null.
    mGeofencePendingIntent = null;

    // Retrieve an instance of the SharedPreferences object.
    mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, MODE_PRIVATE);

    // Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default.
    mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false);
    setButtonsEnabledState();

    // Get the geofences used. Geofence data is hard coded in this sample.
    populateGeofenceList();

    // Kick off the request to build GoogleApiClient.
    buildGoogleApiClient();
    autocompleteView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            final String value = s.toString();

            // Remove all callbacks and messages
            mThreadHandler.removeCallbacksAndMessages(null);

            // Now add a new one
            mThreadHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // Background thread

                    mAdapter.resultList = mAdapter.mPlaceAPI.autocomplete(value);

                    // Footer
                    if (mAdapter.resultList.size() > 0)
                        mAdapter.resultList.add("footer");

                    // Post to Main Thread
                    mThreadHandler.sendEmptyMessage(1);
                }
            }, 500);
        }

        @Override
        public void afterTextChanged(Editable s) {
            //doAfterTextChanged();
        }
    });
    if (mThreadHandler == null) {
        // Initialize and start the HandlerThread
        // which is basically a Thread with a Looper
        // attached (hence a MessageQueue)
        mHandlerThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();

        // Initialize the Handler
        mThreadHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    ArrayList<String> results = mAdapter.resultList;

                    if (results != null && results.size() > 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mAdapter.notifyDataSetChanged();
                                //stuff that updates ui

                            }
                        });

                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                //stuff that updates ui
                                mAdapter.notifyDataSetInvalidated();

                            }
                        });

                    }
                }
            }
        };
    }
    GetID();

}