Example usage for android.location Address getLatitude

List of usage examples for android.location Address getLatitude

Introduction

In this page you can find the example usage for android.location Address getLatitude.

Prototype

public double getLatitude() 

Source Link

Document

Returns the latitude of the address if known.

Usage

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 . ja  v a 2 s .  c  o  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();

}

From source file:eu.trentorise.smartcampus.jp.PlanNewJourneyFragment.java

private void findAddressForField(final String field, Location location) {
    List<Address> hereAddressesList = new SCGeocoder(getSherlockActivity()).findAddressesAsync(location);
    if (hereAddressesList != null && !hereAddressesList.isEmpty()) {
        Address hereAddress = hereAddressesList.get(0);
        savePosition(hereAddress, field);
    } else {/*from www  .  j  a  v a2 s. c om*/
        Address customAddress = new Address(Locale.getDefault());
        customAddress.setLatitude(location.getLatitude());
        customAddress.setLongitude(location.getLongitude());
        customAddress.setAddressLine(0, "LON " + Double.toString(customAddress.getLongitude()) + ", LAT "
                + Double.toString(customAddress.getLatitude()));
        savePosition(customAddress, field);
    }
}

From source file:org.ohmage.reminders.types.location.LocTrigMapsActivity.java

/**
 * Converts an address to a marker to show on the map
 *
 * @param adr/*  w  ww  . j a va 2 s .c  om*/
 * @return
 */
private MarkerOptions addressToMarker(Address adr) {
    StringBuilder addrText = new StringBuilder();

    int addrLines = adr.getMaxAddressLineIndex();
    for (int i = 0; i < Math.min(2, addrLines); i++) {
        addrText.append(adr.getAddressLine(i)).append("\n");
    }
    return new MarkerOptions().position(new LatLng(adr.getLatitude(), adr.getLongitude()))
            .title(addrText.toString());
}

From source file:org.onebusaway.android.report.ui.InfrastructureIssueActivity.java

/**
 * Converts plain address string to Location object
 *
 * @param addressString takes address string
 * @return Location of given address String
 *//* www.  j  a  v a2 s. c  o  m*/
public Location getLocationByAddress(String addressString) {
    Geocoder coder = new Geocoder(this);
    List<Address> addressList;
    Location location;

    try {
        addressList = coder.getFromLocationName(addressString, 3);
        if (addressList == null || addressList.size() == 0) {
            return null;
        }
        Address address = addressList.get(0);

        location = new Location("");
        location.setLatitude(address.getLatitude());
        location.setLongitude(address.getLongitude());

        return location;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:eu.trentorise.smartcampus.jp.PlanNewJourneyFragment.java

private void savePosition(Address address, String field) {
    EditText text = null;/*  w w  w .j a  va  2  s. c  o m*/
    ImageButton imgBtn = null;

    String s = "";
    for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
        s += address.getAddressLine(i) + " ";
    }
    s = s.trim();

    if (field.equals(FROM)) {
        fromPosition = new Position(address.getAddressLine(0), null, null,
                Double.toString(address.getLongitude()), Double.toString(address.getLatitude()));
        if (getView() != null) {
            text = (EditText) getView().findViewById(R.id.plannew_from_text);
            imgBtn = (ImageButton) getView().findViewById(R.id.plannew_from_star);
        }
    } else if (field.equals(TO)) {
        toPosition = new Position(address.getAddressLine(0), null, null,
                Double.toString(address.getLongitude()), Double.toString(address.getLatitude()));

        if (getView() != null) {
            text = (EditText) getView().findViewById(R.id.plannew_to_text);
            imgBtn = (ImageButton) getView().findViewById(R.id.plannew_to_star);
        }
    }

    if (text != null) {
        text.setFocusable(false);
        text.setFocusableInTouchMode(false);
        text.setText(s);
        text.setFocusable(true);
        text.setFocusableInTouchMode(true);
    }

    if (imgBtn != null) {
        for (Position p : userPrefsHolder.getFavorites()) {
            if (address.getAddressLine(0).equalsIgnoreCase(p.getName())
                    || (address.getLatitude() == Double.parseDouble(p.getLat())
                            && address.getLongitude() == Double.parseDouble(p.getLon()))) {
                imgBtn.setImageResource(R.drawable.ic_fav_star_active);
                imgBtn.setTag(true);
            }
        }
    }
}

From source file:fr.univsavoie.ltp.client.MainActivity.java

/**
 * Geocoding of the destination address//from  w w w  .j a v a  2  s  . co  m
 */
public void handleSearchLocationButton() {
    EditText destinationEdit = (EditText) findViewById(R.id.editDestination);
    //Hide the soft keyboard:
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(destinationEdit.getWindowToken(), 0);

    String destinationAddress = destinationEdit.getText().toString();
    GeocoderNominatim geocoder = new GeocoderNominatim(this);
    try {
        List<Address> foundAdresses = geocoder.getFromLocationName(destinationAddress, 1);
        if (foundAdresses.size() == 0) { //if no address found, display an error
            Toast.makeText(this, R.string.toast_address, Toast.LENGTH_SHORT).show();
        } else {
            Address address = foundAdresses.get(0); //get first address
            destinationPoint = new GeoPoint(address.getLatitude(), address.getLongitude());
            markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX,
                    R.string.destination, R.drawable.marker_destination, -1);
            getRoadAsync();
            map.getController().setCenter(destinationPoint);
        }
    } catch (Exception e) {
        Toast.makeText(this, R.string.toast_geocode, Toast.LENGTH_SHORT).show();
    }
}

From source file:info.wncwaterfalls.app.ResultsMapFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    int count = cursor.getCount();
    if (count == 0) {
        Context context = getActivity();
        CharSequence text = "No results found for your search.";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();//from ww  w  .j  a  va 2s .  co  m
    } else {
        // Put the results on a map!
        GoogleMap googleMap = mMapView.getMap();
        double searchLocationDistanceM = 0;
        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
        if (cursor.moveToFirst()) {
            // First, add the "searched for" location, if it was a location search.
            Location originLocation = new Location("");
            Address originAddress = sLocationQueryListener.getOriginAddress();
            if (originAddress != null) {
                // Get searched-for distance and convert to meters.
                short searchLocationDistance = sLocationQueryListener.getSearchLocationDistance();
                searchLocationDistanceM = searchLocationDistance * 1609.34;

                // Build up a list of Address1, Address2, Address3, if present.
                ArrayList<String> addressList = new ArrayList<String>();
                for (int i = 0; i <= 3; i++) {
                    String line = originAddress.getAddressLine(i);
                    if (line != null && line.length() > 0) {
                        addressList.add(line);
                    }
                }

                String addressDesc = TextUtils.join("\n", addressList);
                if (addressDesc == "") {
                    addressDesc = originAddress.getFeatureName();
                }
                if (addressDesc == "") {
                    addressDesc = "Searched Location";
                }

                // Create the LatLng and the map marker.
                LatLng originLatLng = new LatLng(originAddress.getLatitude(), originAddress.getLongitude());
                googleMap.addMarker(new MarkerOptions().position(originLatLng)
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                        .title(addressDesc));

                boundsBuilder.include(originLatLng); // In case only one result :)

                // Translate into a Location for distance comparison.
                originLocation.setLatitude(originAddress.getLatitude());
                originLocation.setLongitude(originAddress.getLongitude());
            } else {
                // Not a location search; don't add point for searched-for location
                // and don't check radius from that point.
                //Log.d(TAG, "Skipped adding origin address to map.");
            }

            // Next, add the results waterfalls.
            // Use do...while since we're already at the first result.
            do {
                // Get some data from the db
                Long waterfallId = cursor.getLong(AttrDatabase.COLUMNS.indexOf("_id"));
                double lat = cursor.getDouble(AttrDatabase.COLUMNS.indexOf("geo_lat"));
                double lon = cursor.getDouble(AttrDatabase.COLUMNS.indexOf("geo_lon"));

                // Make sure this one's actually within our search radius. SQL only checked
                // the bounding box.
                Location waterfallLocation = new Location("");
                waterfallLocation.setLatitude(lat);
                waterfallLocation.setLongitude(lon);

                if (originAddress == null
                        || (originLocation.distanceTo(waterfallLocation) <= searchLocationDistanceM)) {
                    // Not a location search (originAddress is null: show all) or within radius.
                    // Display on map.
                    String name = cursor.getString(AttrDatabase.COLUMNS.indexOf("name"));

                    LatLng waterfallLatLng = new LatLng(lat, lon);
                    Marker waterfallMarker = googleMap.addMarker(new MarkerOptions().position(waterfallLatLng)
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                            .title(name));

                    // Save the id so we can retrieve it when clicked
                    mMarkersToIds.put(waterfallMarker, waterfallId);
                    boundsBuilder.include(waterfallLatLng);
                }

            } while (cursor.moveToNext());

            // Zoom and center the map to bounds
            mResultBounds = boundsBuilder.build();
            zoomToBounds();
        }
    }
}

From source file:eu.trentorise.smartcampus.jp.PlanNewJourneyFragment.java

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

    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(FROM)) {
            fromPosition = (Position) savedInstanceState.getSerializable(FROM);
        }//from w  ww .  ja  va  2s. c  om

        if (savedInstanceState.containsKey(TO)) {
            toPosition = (Position) savedInstanceState.getSerializable(TO);
        }

        if (savedInstanceState.containsKey(FROM_STAR)) {
            fromFav = savedInstanceState.getBoolean(FROM_STAR);
        }

        if (savedInstanceState.containsKey(TO_STAR)) {
            toFav = savedInstanceState.getBoolean(TO_STAR);
        }
    }

    Address from = null, to = null;
    if (getArguments() != null) {
        from = (Address) getArguments().getSerializable(getString(R.string.navigate_arg_from));
        to = (Address) getArguments().getSerializable(getString(R.string.navigate_arg_to));
    } else if (getActivity().getIntent() != null) {
        if (getActivity().getIntent().getData() != null) {
            // is it a google url?
            Map<String, List<String>> locations = JPHelper
                    .getLocationFromUrl(getActivity().getIntent().getData().toString());
            String fromString = null;
            String toString = null;
            from = getLocationsFromParam("saddr", from, locations, fromString);
            to = getLocationsFromParam("daddr", to, locations, toString);
        } else {
            from = (Address) getActivity().getIntent()
                    .getParcelableExtra(getString(R.string.navigate_arg_from));
            to = (Address) getActivity().getIntent().getParcelableExtra(getString(R.string.navigate_arg_to));
        }
    }

    if (from != null) {
        Location location = new Location("");
        location.setLatitude(from.getLatitude());
        location.setLongitude(from.getLongitude());
        findAddressForField(FROM, location);
    }

    if (to != null) {
        Location location = new Location("");
        location.setLatitude(to.getLatitude());
        location.setLongitude(to.getLongitude());
        findAddressForField(TO, location);
    }
}

From source file:edu.usf.cutr.opentripplanner.android.fragments.MainFragment.java

/**
 * Zooms to address or to address and the location of the other marker if it's
 * not the first marker.//from   w w w .j av  a 2  s . co  m
 * <p>
 * If the other location is "MyLocation" will also be included in zoom.
 *
 * @param isStartLocation if true address is for start location
 * @param address         with the location to zoom at
 */
public void zoomToGeocodingResult(boolean isStartLocation, Address address) {
    LatLng latlng = new LatLng(address.getLatitude(), address.getLongitude());
    LatLng mCurrentLatLng = getLastLocation();

    if (isStartLocation) {
        if (mIsStartLocationChangedByUser) {
            if (mEndMarker != null) {
                zoomToTwoPoints(latlng, mEndMarkerPosition);
            } else if (mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_DESTINATION_IS_MY_LOCATION, false)) {
                if (mCurrentLatLng == null) {
                    Toast.makeText(mApplicationContext,
                            mApplicationContext.getResources().getString(
                                    R.string.toast_tripplanner_current_location_error),
                            Toast.LENGTH_LONG).show();
                } else {
                    zoomToTwoPoints(latlng, mCurrentLatLng);
                }
            } else {
                zoomToLocation(latlng);
            }
        }
    } else {
        if (mIsEndLocationChangedByUser) {
            if (mStartMarker != null) {
                zoomToTwoPoints(mStartMarkerPosition, latlng);
            } else if (mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, false)) {
                if (mCurrentLatLng == null) {
                    Toast.makeText(mApplicationContext,
                            mApplicationContext.getResources().getString(
                                    R.string.toast_tripplanner_current_location_error),
                            Toast.LENGTH_LONG).show();
                } else {
                    zoomToTwoPoints(mCurrentLatLng, latlng);
                }
            } else {
                zoomToLocation(latlng);
            }
        }
    }
}

From source file:edu.usf.cutr.opentripplanner.android.fragments.MainFragment.java

/**
 * Wrapper to other functions: moves the marker to the location included
 * in the address, updates text box and zooms to that position.
 * <p>//  w ww .  ja v a  2s. c  om
 * This only happens if the new location is closer than a constant to
 * marker previous location. Otherwise address is only used as reference
 * and text box is updated to "Marker close to [address]".
 *
 * @param isStartMarker if true start marker will be changed
 * @param address       will location and text information
 */
public void moveMarkerRelative(Boolean isStartMarker, Address address) {
    float results[] = new float[1];
    double addressLat = address.getLatitude();
    double addressLon = address.getLongitude();

    Marker marker;
    if (isStartMarker) {
        marker = mStartMarker;
        mStartAddress = address;
    } else {
        marker = mEndMarker;
        mEndAddress = address;
    }

    Location.distanceBetween(marker.getPosition().latitude, marker.getPosition().longitude, addressLat,
            addressLon, results);

    if (results[0] < OTPApp.MARKER_GEOCODING_MAX_ERROR) {
        LatLng newLatlng = new LatLng(addressLat, addressLon);
        setMarkerPosition(isStartMarker, newLatlng);
        setTextBoxLocation(getStringAddress(address, false), isStartMarker);
    } else {
        setTextBoxLocation(getResources().getString(R.string.text_box_close_to_marker) + " "
                + getStringAddress(address, false), isStartMarker);
    }

}