Example usage for android.location Location distanceTo

List of usage examples for android.location Location distanceTo

Introduction

In this page you can find the example usage for android.location Location distanceTo.

Prototype

public float distanceTo(Location dest) 

Source Link

Document

Returns the approximate distance in meters between this location and the given location.

Usage

From source file:uk.co.spookypeanut.wake_me_at.WakeMeAtService.java

@Override
public void onLocationChanged(Location location) {
    lastLocation.setToNow();//from w  w  w  . j a  va  2  s  . co m
    Log.v(LOG_NAME, "onLocationChanged(" + lastLocation.toMillis(false) + ")");
    mHandler.removeCallbacks(mCheckLocationAge);
    if (mWarningOn) {
        mHandler.postDelayed(mCheckLocationAge, mMinTime);
    }

    mCurrLocation = location;
    mMetresAway = location.distanceTo(mFinalDestination);
    // message is, e.g. You are 200m from Welwyn North
    String message = String.format(getString(R.string.notif_full), uc.out(mMetresAway), mNick);
    mBuilder.setContentText(message);
    // Turn off the sound and vibrate, in case they were turned
    // on by the old location warning
    //mNotification.defaults &= ~Notification.DEFAULT_SOUND;
    //mNotification.defaults &= ~Notification.DEFAULT_VIBRATE;
    mNM.notify(ALARMNOTIFY_ID, mBuilder.build());
    if (mMetresAway < uc.toMetres(mRadius)) {
        soundAlarm();
    }
    updateAlarm();
}

From source file:com.ibm.mf.geofence.MFGeofencingManager.java

/**
 * Add the specified geofences to the monitored geofences.
 * @param geofences the geofences to add.
 *///from   w w w  .j a  v a 2s .com
void monitorGeofences(List<PersistentGeofence> geofences) {
    if (!geofences.isEmpty()) {
        log.debug("monitorGeofences(" + geofences + ")");
        List<Geofence> list = new ArrayList<>(geofences.size());
        List<Geofence> noTriggerList = new ArrayList<>(geofences.size());
        Location last = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        for (PersistentGeofence geofence : geofences) {
            Geofence fence = new Geofence.Builder().setRequestId(geofence.getCode())
                    .setCircularRegion(geofence.getLatitude(), geofence.getLongitude(),
                            (float) geofence.getRadius())
                    .setExpirationDuration(Geofence.NEVER_EXPIRE).setNotificationResponsiveness(10_000)
                    .setLoiteringDelay(300000)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

            Location location = new Location(LocationManager.NETWORK_PROVIDER);
            location.setLatitude(geofence.getLatitude());
            location.setLongitude(geofence.getLongitude());
            if ((mMode != MODE_REBOOT) || (last == null)
                    || (location.distanceTo(last) > geofence.getRadius())) {
                list.add(fence);
            } else {
                // if already in geofence, do not trigger upon registration.
                noTriggerList.add(fence);
            }
        }
        registerFencesForMonitoring(list, GeofencingRequest.INITIAL_TRIGGER_ENTER);
        registerFencesForMonitoring(noTriggerList, 0);
    }
}

From source file:edu.utexas.quietplaces.services.PlacesUpdateService.java

/**
 * {@inheritDoc}/*  w w w . j  a  va2 s  .com*/
 * Checks the battery and connectivity state before removing stale venues
 * and initiating a server poll for new venues around the specified
 * location within the given radius.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    //noinspection deprecation
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = prefs.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (!backgroundAllowed && inBackground)
        return;

    // Extract the location and radius around which to conduct our search.
    Location location = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
    int radius = PlacesConstants.PLACES_SEARCH_RADIUS;

    Bundle extras = intent.getExtras();
    if (intent.hasExtra(PlacesConstants.EXTRA_KEY_LOCATION)) {
        location = (Location) (extras.get(PlacesConstants.EXTRA_KEY_LOCATION));
        radius = extras.getInt(PlacesConstants.EXTRA_KEY_RADIUS, PlacesConstants.PLACES_SEARCH_RADIUS);
    }

    // Check if we're in a low battery situation.
    IntentFilter batIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent battery = registerReceiver(null, batIntentFilter);
    lowBattery = getIsLowBattery(battery);

    // Check if we're connected to a data network, and if so - if it's a mobile network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    mobileData = activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;

    // If we're not connected, enable the connectivity receiver and disable the location receiver.
    // There's no point trying to poll the server for updates if we're not connected, and the
    // connectivity receiver will turn the location-based updates back on once we have a connection.
    if (!isConnected) {
        Log.w(TAG, "Not connected!");
    } else {
        // If we are connected check to see if this is a forced update (typically triggered
        // when the location has changed).
        boolean doUpdate = intent.getBooleanExtra(PlacesConstants.EXTRA_KEY_FORCEREFRESH, false);

        // If it's not a forced update (for example from the Activity being restarted) then
        // check to see if we've moved far enough, or there's been a long enough delay since
        // the last update and if so, enforce a new update.
        if (!doUpdate) {
            // Retrieve the last update time and place.
            long lastTime = prefs.getLong(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_TIME, Long.MIN_VALUE);
            float lastLat;
            try {
                lastLat = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LAT, Float.MIN_VALUE);
            } catch (ClassCastException e) {
                // handle legacy version
                lastLat = Float.MIN_VALUE;
            }
            float lastLng;
            try {
                lastLng = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LNG, Float.MIN_VALUE);
            } catch (ClassCastException e) {
                lastLng = Float.MIN_VALUE;
            }
            Location lastLocation = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
            lastLocation.setLatitude(lastLat);
            lastLocation.setLongitude(lastLng);

            long currentTime = System.currentTimeMillis();
            float distanceMovedSinceLast = lastLocation.distanceTo(location);
            long elapsedTime = currentTime - lastTime;

            Log.i(TAG, "Last Location in places update service: " + lastLocation + " distance to current: "
                    + distanceMovedSinceLast + " - current: " + location);

            if (location == null) {
                Log.w(TAG, "Location is null...");
            }
            // If update time and distance bounds have been passed, do an update.
            else if (lastTime < currentTime - PlacesConstants.MAX_TIME_BETWEEN_PLACES_UPDATE) {
                Log.i(TAG, "Time bounds passed on places update, " + elapsedTime / 1000 + "s elapsed");
                doUpdate = true;
            } else if (distanceMovedSinceLast > PlacesConstants.MIN_DISTANCE_TRIGGER_PLACES_UPDATE) {
                Log.i(TAG, "Distance bounds passed on places update, moved: " + distanceMovedSinceLast
                        + " meters, time elapsed:  " + elapsedTime / 1000 + "s");
                doUpdate = true;
            } else {
                Log.d(TAG, "Time/distance bounds not passed on places update. Moved: " + distanceMovedSinceLast
                        + " meters, time elapsed: " + elapsedTime / 1000 + "s");
            }
        }

        if (location == null) {
            Log.e(TAG, "null location in onHandleIntent");
        } else if (doUpdate) {
            // Refresh the prefetch count for each new location.
            prefetchCount = 0;
            // Remove the old locations - TODO: we flush old locations, but if the next request
            // fails we are left high and dry
            removeOldLocations(location, radius);
            // Hit the server for new venues for the current location.
            refreshPlaces(location, radius, null);

            // Tell the main activity about the new results.
            Intent placesUpdatedIntent = new Intent(Config.ACTION_PLACES_UPDATED);
            LocalBroadcastManager.getInstance(this).sendBroadcast(placesUpdatedIntent);

        } else {
            Log.i(TAG, "Place List is fresh: Not refreshing");
        }

        // Retry any queued checkins.
        /*
                    Intent checkinServiceIntent = new Intent(this, PlaceCheckinService.class);
                    startService(checkinServiceIntent);
        */
    }
    Log.d(TAG, "Place List Download Service Complete");
}

From source file:com.ibm.mf.geofence.demo.MapsActivity.java

void initGeofences() {
    try {/*  w w  w .  j  av a 2s  . c o m*/
        final List<MFGeofence> fences = DemoUtils.getAllGeofencesFromDB();
        log.debug("initGeofences() " + (fences == null ? 0 : fences.size()) + " fences in local DB");
        geofenceHolder.clearFences();
        geofenceHolder.addFences(fences);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (MFGeofence g : fences) {
                        boolean active = false;
                        if (currentLocation != null) {
                            Location loc = new Location(LocationManager.NETWORK_PROVIDER);
                            loc.setLatitude(g.getLatitude());
                            loc.setLongitude(g.getLongitude());
                            loc.setTime(System.currentTimeMillis());
                            active = loc.distanceTo(currentLocation) <= g.getRadius();
                        }
                        refreshGeofenceInfo(g, active);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    final ArrayList<String> infoAndName = new ArrayList<String>();
    try {/*from   ww  w.j av a2s.  c  o m*/
        for (int i = 0; i < usersFound.length(); i++) {
            infoAndName.add(usersFound.getJSONObject(i).getString("name"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Location geoPointLocation = new Location("geoPoint");
            try {
                infoAndName.clear();
                for (int i = 0; i < usersFound.length(); i++) {
                    String appendedText = "";
                    if (!usersFound.getJSONObject(i).has("channel")) {
                        geoPointLocation.setLongitude(usersFound.getJSONObject(i).getDouble("lon"));
                        geoPointLocation.setLatitude(usersFound.getJSONObject(i).getDouble("lat"));
                        float distance = location.distanceTo(geoPointLocation) / 1000;
                        appendedText = String.format("%.1f", distance) + "Km";
                    } else {
                        appendedText = usersFound.getJSONObject(i).getString("channel");
                    }
                    infoAndName.add(appendedText + usersFound.getJSONObject(i).getString("name"));
                    Log.e("infoandname", infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1));
                    Toast.makeText(mContext, infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1),
                            Toast.LENGTH_LONG).show();

                    // infoAndName tem a informacao de distancia ou canal e o nome. Precisa editar
                    //essa parte de baixo pra usar o infoAndName.
                    ArrayList<String> friendsEmails = new ArrayList<>();

                    friendsEmails.addAll(infoAndName);

                    friendsEmails = new ArrayList<>();
                    for (ArrayList<String> array : ServerInformation.getAllActiveListeners()) {
                        friendsEmails.addAll(array);
                        while (friendsEmails.contains(connectedEmail))
                            friendsEmails.remove(connectedEmail);
                    }
                    EmailListAdapter listAdapter = new EmailListAdapter(mContext, R.layout.adapter_email_list,
                            friendsEmails);
                    ListView emails = (ListView) ((Activity) mContext)
                            .findViewById(R.id.gps_friends_from_drawer);
                    emails.setAdapter(listAdapter);

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

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    // Minimum of 2 minutes between checks (120000 milisecs).
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 0, locationListener);
}

From source file:com.example.run_tracker.TrackingService.java

@Override
public void onLocationChanged(Location arg0) {
    Log.v(TAG, "onLocationChanged");
    // add the next point to list and broadcast the message
    if (mStarted) {
        // add the new point to the list
        if (!mCoursePoints.isEmpty()) {
            Location prev_point = new Location("point A"); // previous location
            prev_point.setLatitude(get_last_point(mCoursePoints).latitude);
            prev_point.setLongitude(get_last_point(mCoursePoints).longitude);
            // sometimes when we lose gps signal the first from second
            // location are 3000km apart or more
            // so we check this in order to be more precise
            if (arg0.distanceTo(prev_point) < 15) {
                mDistance += arg0.distanceTo(prev_point);
            }//from ww w .  ja  v a2s  .  c om
        } else {
            mDistance = 0;
        }
        mCoursePoints.add(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
        mLastPoint = new LatLng(arg0.getLatitude(), arg0.getLongitude());
        // broadcast message ;
        sendlocation();
    }
}

From source file:com.careme.apvereda.careme.AccumulatorService.java

private void resetList(Location loc) {
    List<RoutinePlace> routines = db.getAllRoutinePlaces();
    Location l = new Location("Laux");
    Set<String> ids = new HashSet<String>();
    SharedPreferences shared = getApplicationContext().getSharedPreferences("monitor", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = shared.edit();
    editor.putString("probably", Integer.toString(-1));
    editor.commit();//from   w  w  w . j a  v  a  2 s.c o m
    for (RoutinePlace r : routines) {
        l.setLatitude(r.getPlace().getLatitude());
        l.setLongitude(r.getPlace().getLongitude());
        if (loc.distanceTo(l) < 60) {
            ids.add(r.getRoutine().getId() + "");
            long t1 = new Date().getTime() % 86400000;
            long t2 = r.getRoutine().getStart().getTime() % 86400000;
            if (Math.abs(t1 - t2) < 1800000) {
                editor.putString("probably", r.getRoutine().getId() + "");
                editor.commit();
            }
        }
    }
    editor.putStringSet("routines", ids);
    shownot("Reseteamos lista de monitorizacin");
    editor.commit();
}

From source file:eu.hydrologis.geopaparazzi.chart.ProfileChartActivity.java

/**
 * Create a dataset based on supplied data that are supposed to be coordinates and elevations for a profile view.
 *//*from  w  w w.ja  v  a  2  s. c  om*/
public void createDatasetFromProfile() throws Exception {
    DynamicDoubleArray lonArray = line.getLonList();
    DynamicDoubleArray latArray = line.getLatList();
    DynamicDoubleArray elevArray = line.getAltimList();
    List<String> dates = line.getDateList();

    double previousLat = 0;
    double previousLon = 0;
    double previousElev = 0;
    double summedDistance = 0.0;
    long previousTime = 0;

    List<Double> xList1 = new ArrayList<Double>(lonArray.size());
    List<Double> yList1 = new ArrayList<Double>(lonArray.size());
    List<Double> yList2 = new ArrayList<Double>(lonArray.size());
    elevDifference = 0;
    for (int i = 0; i < lonArray.size(); i++) {
        double elev = elevArray.get(i);
        double lat = latArray.get(i);
        double lon = lonArray.get(i);
        String dateStr = dates.get(i);
        long time = Long.parseLong(dateStr);

        double distance = 0.0;
        if (i > 0) {
            Location thisLoc = new Location("dummy1"); //$NON-NLS-1$
            thisLoc.setLongitude(lon);
            thisLoc.setLatitude(lat);
            Location thatLoc = new Location("dummy2"); //$NON-NLS-1$
            thatLoc.setLongitude(previousLon);
            thatLoc.setLatitude(previousLat);
            distance = thisLoc.distanceTo(thatLoc);

            double diff = elev - previousElev;
            if (diff > 0)
                elevDifference = elevDifference + diff;

            double timeSeconds = (time - previousTime) / 1000.0;
            double speed = Math.sqrt(diff * diff + distance * distance) / timeSeconds;

            yList2.add(speed);
        } else {
            yList2.add(0.0);
        }

        previousLat = lat;
        previousLon = lon;
        previousElev = elev;
        previousTime = time;

        summedDistance = summedDistance + distance;

        xList1.add(summedDistance);
        yList1.add(elev);
    }

    // Setup the Series
    seriesElev = new SimpleXYSeries(xList1, yList1, "Elev [m]");
    seriesSpeed = new SimpleXYSeries(xList1, yList2, "Speed [m/s]");
}

From source file:com.golfmarin.golf.HoleActivity.java

/**
 * Calculates distances to placements and updates the UI
 *
 * @param location Current watch location
 *//*from  ww  w  . j a v a 2 s .  co  m*/

private void updateDisplay(Location location) {
    // float accuracy;
    // accuracy = location.getAccuracy();
    // Only use whe there is a current hole defined.
    if (currentHole != null) {

        float conv = (float) 1.0936133;
        float yards = location.distanceTo(currentHole.getLocation("front")) * conv;
        String front = String.valueOf((int) yards);
        frontView.setText(front);

        yards = location.distanceTo(currentHole.getLocation("middle")) * conv;
        String middle = String.valueOf((int) yards);
        middleView.setText(middle);

        yards = location.distanceTo(currentHole.getLocation("back")) * conv;
        String back = String.valueOf((int) yards);
        backView.setText(back);

        // Keep the hole number display current
        String holeViewText = ("Hole " + currentHole.holeNum);
        holeView.setText(holeViewText);

        // Make sure startup elements are normal
        progressView.setVisibility(View.GONE);
    }
}

From source file:ca.uwaterloo.magic.goodhikes.MapsActivity.java

public String toJSON() {

    JSONObject jsonObj = new JSONObject();
    if (selectedRoute == null || selectedRoute.getId() == -1)
        return null;
    Route curr = selectedRoute;/*from   w  w w . j  a  v a2 s  .  c o m*/
    Log.d("maps:first_coord", String.valueOf(curr.getStartCoordinates()));
    float max_speed = 0, total_speed = 0;
    float distance = 0;
    ArrayList<LocationPoint> trace = curr.getTrace();
    for (int i = 0; i < curr.size(); i++) {
        Location location = trace.get(i);
        if (i > 0) {
            //Log.d(LOG_TAG, i-1 + " to " + i + ": " + location.distanceTo(trace.get(i-1)));
            distance += location.distanceTo(trace.get(i - 1));
        }
        if (location.getSpeed() > max_speed)
            max_speed = location.getSpeed();
        total_speed += location.getSpeed();
    }
    try {
        jsonObj.put("user_name", curr.getUser().getUsername());
        jsonObj.put("route_name", curr.getDescription());
        jsonObj.put("start_time", curr.getDateStartString() + ", " + curr.getTimeStart());
        jsonObj.put("end_time", curr.getDateEndString() + ", " + curr.getTimeEnd());
        jsonObj.put("duration", curr.getDurationString());
        jsonObj.put("distance", distance / 1000);
        jsonObj.put("aver_speed", total_speed / curr.size());
        jsonObj.put("max_speed", max_speed);
        jsonObj.put("num_waypoints", curr.size());
        jsonObj.put("private", curr.getPrivate() == true ? "True" : "False");

    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d(LOG_TAG, "JSON String: " + jsonObj.toString());
    return jsonObj.toString();
}