Example usage for android.location Geocoder getFromLocationName

List of usage examples for android.location Geocoder getFromLocationName

Introduction

In this page you can find the example usage for android.location Geocoder getFromLocationName.

Prototype

public List<Address> getFromLocationName(String locationName, int maxResults) throws IOException 

Source Link

Document

Returns an array of Addresses that are known to describe the named location, which may be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre Parkway, Mountain View, CA", an airport code such as "SFO", etc..

Usage

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

/**
 * Find Coordinates for a given address//from w w w.j av a2s.com
 *
 * @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.licenta.android.licenseapp.location.MapFragment.java

public void onShow(View view) {
    LatLng lastKnownLatLng = null;// w w  w . j a  v a 2  s.c  om
    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: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);
    }//w  w w .  j av  a2  s . c o  m

    return extractAddress(addresses);
}

From source file:com.example.tj.weather.WeatherActivity.java

private void wearSearchRequest(Intent intent) {
    Log.i("onNewIntent()", "called");

    String location = intent.getStringExtra("message");

    if (location != null) {
        Geocoder geocoder = new Geocoder(this);

        List<Address> addressList = null;

        try {/*from   w  ww .  j  av  a  2  s  .  c o m*/
            addressList = geocoder.getFromLocationName(location, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (addressList != null) {
            Address address = addressList.get(0);

            if (address != null) {
                onCityChanged(address.getLocality().toLowerCase(), address.getAdminArea().toLowerCase());
            }
        }
    }
}

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

@Override
protected void onServiceBound() {
    T.UI();//ww w .  j a va2  s.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.ant.sunshine.app.activities.MainActivity.java

private void reloadLocationIfChanged(String location) {
    if (location != null && !location.equals(mLocation)) {
        Fragment fragment = getFragmentById();
        if (isForecastFragment(fragment)) {
            reloadLocation();// www .  j a v a2 s .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.vishnuvalleru.travelweatheralertsystem.MainActivity.java

@SuppressLint("NewApi")
@Override//from  ww  w.j  a v  a  2 s  .c  o m
protected void onCreate(Bundle savedInstanceState) {
    Bundle b = getIntent().getExtras();
    String fromLocation = b.getString("from");
    String toLocation = b.getString("to");
    Geocoder coder = new Geocoder(this);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    try {
        ArrayList<Address> frmAddresses = (ArrayList<Address>) coder.getFromLocationName(fromLocation, 50);
        ArrayList<Address> toAddresses = (ArrayList<Address>) coder.getFromLocationName(toLocation, 50);
        for (Address add : frmAddresses) {
            src_long = add.getLongitude();
            src_lat = add.getLatitude();
        }
        for (Address add : toAddresses) {
            dest_long = add.getLongitude();
            dest_lat = add.getLatitude();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    LatLng srcLatLng = new LatLng(src_lat, src_long);
    LatLng destLatLng = new LatLng(dest_lat, dest_long);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager myFragmentManager = getFragmentManager();
    MapFragment myMapFragment = (MapFragment) myFragmentManager.findFragmentById(R.id.map);

    myMap = myMapFragment.getMap();
    myMap.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
    myMap.setOnMapClickListener(new OnMapClickListener() {

        @Override
        public void onMapClick(LatLng point) {
            // Drawing marker on the map
            drawMarker(point);
        }
    });

    // Enabling MyLocation in Google Map
    myMap.setMyLocationEnabled(true);
    myMap.getUiSettings().setZoomControlsEnabled(true);
    myMap.getUiSettings().setCompassEnabled(true);
    myMap.getUiSettings().setMyLocationButtonEnabled(true);
    myMap.getUiSettings().setAllGesturesEnabled(true);
    myMap.setTrafficEnabled(true);
    myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(destLatLng, 6));
    markerOptions = new MarkerOptions();

    drawMarker(srcLatLng);
    drawMarker(destLatLng);

    connectAsyncTask _connectAsyncTask = new connectAsyncTask();
    _connectAsyncTask.execute();
}

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 w w .j a  v a 2 s. c  om
    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();

}

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;//  ww w  .j av  a2 s.  c  o m
        // 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.nearnotes.NoteEdit.java

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
    mBodyText.requestFocus();// ww  w .  jav  a 2s  .co m
    autoCompView.setSelection(0);
    tempPosition = position;
    location = (String) adapterView.getItemAtPosition(position);
    Geocoder find = new Geocoder(getActivity());
    try {
        List<Address> AddressList = find.getFromLocationName(location, 10);
        if (AddressList.size() > 0) {
            longitude = AddressList.get(0).getLongitude();
            latitude = AddressList.get(0).getLatitude();
            //if 1st provider does not have data, loop through other providers to find it.
            int count = 0;
            while (longitude == 0 && count < AddressList.size()) {
                longitude = AddressList.get(count).getLongitude();
                latitude = AddressList.get(count).getLatitude();
                count++;
            }
            autoCompView.setTextColor(getResources().getColor(R.color.deepgreen));
        } else {
            StringBuilder sb = new StringBuilder("http://www.nearnotes.com/geocode.php");
            sb.append("?reference=" + String.valueOf(referenceList.get(tempPosition)));
            new NetworkTask().execute(sb.toString());

        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Couldnt received coordinates");
        e.printStackTrace();
    }
}