Java Code Examples for android.location.Location#distanceTo()

The following examples show how to use android.location.Location#distanceTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainFragment.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
private void calcQiblaAngle(@NonNull Location location) {
    mLocation = location;
    if (!"custom".equals(location.getProvider())) {
        mSelCity.setVisibility(View.GONE);
    }
    double lat1 = location.getLatitude();// Latitude of User Location
    double lng1 = location.getLongitude();// Longitude of User Location
    double lat2 = 21.42247;// Latitude of Qaaba (+21.45° north of Equator)
    double lng2 = 39.826198;// Longitude of Qaaba (-39.75° east of Prime Meridian)

    double q = -getDirection(lat1, lng1, lat2, lng2);

    Location loc = new Location(location);
    loc.setLatitude(lat2);
    loc.setLongitude(lng2);
    mQiblaAngle = q;
    mQiblaDistance = location.distanceTo(loc) / 1000;

    notifyListener();

}
 
Example 2
Source File: distanceCache.java    From wifi_backend with GNU General Public License v3.0 6 votes vote down vote up
public synchronized float distanceBetween(Location loc1, Location loc2) {
    cacheKey key = new cacheKey(loc1, loc2);
    cacheKey key1 = new cacheKey(loc2, loc1);
    distanceRec cachedValue = distanceCache.get(key);
    if (cachedValue == null) {
        cachedValue = distanceCache.get(key1);
    }
    if (cachedValue == null) {
        myMisses++;
        cachedValue = new distanceRec();
        cachedValue.distance = loc1.distanceTo(loc2);
        distanceCache.put(key,cachedValue);
    } else
        myHits++;
    return cachedValue.distance;
}
 
Example 3
Source File: ExportAllAndImportAllTest.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the GPX file distance in km.
 */
private double getGpxFileDistance() {
  double distance = 0.0;
  double latitude = GPX_FILE_INIT_LATITUDE;
  double longitude = GPX_FILE_INIT_LONGITUDE;

  Location current = new Location(LocationManager.GPS_PROVIDER);
  current.setLatitude(latitude);
  current.setLongitude(longitude);
  for (int i = 1; i < 10; i++) {
    Location next = new Location(LocationManager.GPS_PROVIDER);
    next.setLatitude(latitude - 0.0005 * i);
    next.setLongitude(longitude + 0.0005 * i);
    distance = distance + next.distanceTo(current) * UnitConversions.M_TO_KM;
    current = next;
  }
  return distance;
}
 
Example 4
Source File: MainActivity.java    From NYU-BusTracker-Android with Apache License 2.0 6 votes vote down vote up
private void setStartAndEndStops() {
    String end = getSharedPreferences(STOP_PREF, MODE_PRIVATE).getString(END_STOP_PREF, "3rd Ave & 14th St");         // Creates or updates cache file.
    String start = getSharedPreferences(STOP_PREF, MODE_PRIVATE).getString(START_STOP_PREF, "715 Broadway");
    if (startStop == null) setStartStop(BusManager.getBusManager().getStopByName(start));
    if (endStop == null) setEndStop(BusManager.getBusManager().getStopByName(end));
    Location l = getLocation();
    if (l != null && System.currentTimeMillis() - onStartTime < 1000) {
        Location startLoc = new Location(""), endLoc = new Location("");
        startLoc.setLatitude(startStop.getLocation().latitude);
        startLoc.setLongitude(startStop.getLocation().longitude);
        endLoc.setLatitude(endStop.getLocation().latitude);
        endLoc.setLongitude(endStop.getLocation().longitude);
        if (l.distanceTo(startLoc) > l.distanceTo(endLoc)) {
            setStartStop(endStop);
        }
    }
}
 
Example 5
Source File: BackendService.java    From DejaVu with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check to see if the coverage area (location) of an RF emitter is close
 * enough to others in a group that we can believably add it to the group.
 * @param location The coverage area of the candidate emitter
 * @param locGroup The coverage areas of the emitters already in the group
 * @return True if location is close to others in group
 */
private boolean locationCompatibleWithGroup(Location location,
                                            Set<Location> locGroup) {

    // If the location is within range of all current members of the
    // group, then we are compatible.
    for (Location other : locGroup) {
        double testDistance = (location.distanceTo(other) -
                location.getAccuracy() -
                other.getAccuracy());

        if (testDistance > 0.0) {
            //Log.d(TAG,"locationCompatibleWithGroup(): "+testDistance);
            return false;
        }
    }
    return true;
}
 
Example 6
Source File: GetLocation.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private static LocationCallback getLocationCallback() {
    return new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            if (locationResult == null) {
                return;
            }
            final Location thisLocation = locationResult.getLastLocation();
            UserError.Log.d(TAG, "Got location update callback!! " + thisLocation);
            if ((lastLocation == null)
                    || thisLocation.getAccuracy() < lastLocation.getAccuracy()
                    || ((thisLocation.getAccuracy() < SKIP_DISTANCE) && (thisLocation.distanceTo(lastLocation) > SKIP_DISTANCE))) {

                lastLocation = thisLocation;
                UserError.Log.d(TAG, "Got location UPDATED element: " + lastLocation);
                Inevitable.task("update-street-location", 6000, () -> lastAddress = getStreetLocation(lastLocation.getLatitude(), lastLocation.getLongitude()));
            }
        }
    };
}
 
Example 7
Source File: MainFragment.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
private void calcQiblaAngle(@NonNull Location location) {
    mLocation = location;
    if (!"custom".equals(location.getProvider())) {
        mSelCity.setVisibility(View.GONE);
    }
    double lat1 = location.getLatitude();// Latitude of User Location
    double lng1 = location.getLongitude();// Longitude of User Location
    double lat2 = 21.42247;// Latitude of Qaaba (+21.45° north of Equator)
    double lng2 = 39.826198;// Longitude of Qaaba (-39.75° east of Prime Meridian)

    double q = -getDirection(lat1, lng1, lat2, lng2);

    Location loc = new Location(location);
    loc.setLatitude(lat2);
    loc.setLongitude(lng2);
    mQiblaAngle = q;
    mQiblaDistance = location.distanceTo(loc) / 1000;

    notifyListener();

}
 
Example 8
Source File: PointF3D.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calculates the 2d distance between two points.
 *
 * @param p the {@link PointF} from which to calculate from.
 * @return the 2d distance.
 */
@SuppressWarnings("nls")
public float distance2d(PointF p) {
    Location thisLoc = new Location("dummy");
    thisLoc.setLongitude(x);
    thisLoc.setLatitude(y);
    Location thatLoc = new Location("dummy");
    thatLoc.setLongitude(p.x);
    thatLoc.setLatitude(p.y);

    return thisLoc.distanceTo(thatLoc);
}
 
Example 9
Source File: AlertLogic.java    From redalert-android with Apache License 2.0 5 votes vote down vote up
public static boolean isNearby(String cityName, Context context) {
    // Get nearby alerts enabled setting
    boolean nearbyEnabled = Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);

    // Are nearby alerts enabled?
    if (!nearbyEnabled) {
        return false;
    }

    // Get current location (last known)
    Location myLocation = LocationLogic.getLocation(context);

    // No recent location?
    if (myLocation == null) {
        return false;
    }

    // Get city geolocation
    Location location = LocationData.getCityLocation(cityName, context);

    // No match?
    if (location == null) {
        return false;
    }

    // Calculate max distance
    double maxDistance = LocationLogic.getMaxDistanceKilometers(context, -1);

    // Get distance to city in KM
    float distance = location.distanceTo(myLocation) / 1000;

    // Distance is less than max?
    if (distance <= maxDistance) {
        // We are nearby!
        return true;
    }

    // No match
    return false;
}
 
Example 10
Source File: LocationUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the distance on the two sphere between the point c0 and the line
 * segment c1 to c2.
 * 
 * @param c0 the first coordinate
 * @param c1 the beginning of the line segment
 * @param c2 the end of the lone segment
 * @return the distance in m (assuming spherical earth)
 */
private static double distance(final Location c0, final Location c1, final Location c2) {
  if (c1.equals(c2)) {
    return c2.distanceTo(c0);
  }

  final double s0lat = c0.getLatitude() * UnitConversions.DEG_TO_RAD;
  final double s0lng = c0.getLongitude() * UnitConversions.DEG_TO_RAD;
  final double s1lat = c1.getLatitude() * UnitConversions.DEG_TO_RAD;
  final double s1lng = c1.getLongitude() * UnitConversions.DEG_TO_RAD;
  final double s2lat = c2.getLatitude() * UnitConversions.DEG_TO_RAD;
  final double s2lng = c2.getLongitude() * UnitConversions.DEG_TO_RAD;

  double s2s1lat = s2lat - s1lat;
  double s2s1lng = s2lng - s1lng;
  final double u = ((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng)
      / (s2s1lat * s2s1lat + s2s1lng * s2s1lng);
  if (u <= 0) {
    return c0.distanceTo(c1);
  }
  if (u >= 1) {
    return c0.distanceTo(c2);
  }
  Location sa = new Location("");
  sa.setLatitude(c0.getLatitude() - c1.getLatitude());
  sa.setLongitude(c0.getLongitude() - c1.getLongitude());
  Location sb = new Location("");
  sb.setLatitude(u * (c2.getLatitude() - c1.getLatitude()));
  sb.setLongitude(u * (c2.getLongitude() - c1.getLongitude()));
  return sa.distanceTo(sb);
}
 
Example 11
Source File: LocalPlace.java    From ratebeer with GNU General Public License v3.0 5 votes vote down vote up
public static LocalPlace from(Place place, Location userLocation) {
	LocalPlace localPlace = new LocalPlace();
	localPlace.place = place;
	if (place.latitude != null && place.longitude != null) {
		localPlace.placeLocation = new Location("LocalPlace");
		localPlace.placeLocation.setLatitude(place.latitude);
		localPlace.placeLocation.setLongitude(place.longitude);
		localPlace.userLocation = userLocation;
		localPlace.distance = userLocation.distanceTo(localPlace.placeLocation);
	}
	return localPlace;
}
 
Example 12
Source File: ConditionsValidator.java    From TowerCollector with Mozilla Public License 2.0 5 votes vote down vote up
public boolean isMinDistanceSatisfied(Location previousLocation, Location currentLocation, int minDistance) {
    // approximate match with 10% tolerance
    float distanceDiff = previousLocation.distanceTo(currentLocation);
    int distanceCondition = minDistance;
    // check conditions
    boolean valid = (1.1f * distanceDiff >= distanceCondition);
    if (!valid)
        Timber.d("isMinDistanceSatisfied(): Failed to achieve destination '%.4f >= %d' condition at 10%% approx. match", distanceDiff, distanceCondition);
    return valid;
}
 
Example 13
Source File: Navigator.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
private void selectNewNextPoint(Location location, int newNextIndex) {
    if (newNextIndex >= 0 && newNextIndex < _nbPointsSimpl) {
        Log.d(TAG, "New _nextIndex: " + _nextIndex + "=>" + newNextIndex);
        _nextIndex = newNextIndex;
        _lastSeenLoc = location;
        _lastSeenDist = location.distanceTo(_pointsSimpl[newNextIndex]);
    }
}
 
Example 14
Source File: RMBTLoopService.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location curLocation)
{
    if (lastTestLocation != null)
    {
        final float distance = curLocation.distanceTo(lastTestLocation);
        loopModeResults.setLastDistance(distance);
        loopModeResults.setLastAccuracy(curLocation.getAccuracy());
        Log.d(TAG, "location distance: " + distance + "; maxMovement: " + loopModeResults.getMaxMovement());
        onAlarmOrLocation(false);    
    }
    lastLocation = curLocation;
}
 
Example 15
Source File: LocationController.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (location == null) {
        return;
    }
    if (lastKnownLocation != null && (this == networkLocationListener || this == passiveLocationListener)) {
        if (!started && location.distanceTo(lastKnownLocation) > 20) {
            setLastKnownLocation(location);
            lastLocationSendTime = SystemClock.elapsedRealtime() - BACKGROUD_UPDATE_TIME + 5000;
        }
    } else {
        setLastKnownLocation(location);
    }
}
 
Example 16
Source File: Distance.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressLint("MissingPermission")
private void calculate(boolean toast) {
    if (getContext() != null) {
        IGISApplication app = (IGISApplication) getContext().getApplicationContext();
        GpsEventSource gpsEventSource = app.getGpsEventSource();
        Location current = gpsEventSource.getLastKnownLocation();
        if (current != null && mLocation != null)
            mValue = current.distanceTo(mLocation);
        else if (toast)
            Toast.makeText(getContext(), R.string.error_no_location, Toast.LENGTH_SHORT).show();
    } else if (toast)
        Toast.makeText(getContext(), R.string.error_no_location, Toast.LENGTH_SHORT).show();
}
 
Example 17
Source File: LocationRepository.java    From android with Apache License 2.0 4 votes vote down vote up
public static float getDistance(Location a, Location b) {
    if (a == null || b == null) return Float.MAX_VALUE;
    return a.distanceTo(b);
}
 
Example 18
Source File: LocationService.java    From AndroidLocationStarterKit with MIT License 4 votes vote down vote up
private boolean filterAndAddLocation(Location location){

        long age = getLocationAge(location);

        if(age > 5 * 1000){ //more than 5 seconds
            Log.d(TAG, "Location is old");
            oldLocationList.add(location);
            return false;
        }

        if(location.getAccuracy() <= 0){
            Log.d(TAG, "Latitidue and longitude values are invalid.");
            noAccuracyLocationList.add(location);
            return false;
        }

        //setAccuracy(newLocation.getAccuracy());
        float horizontalAccuracy = location.getAccuracy();
        if(horizontalAccuracy > 10){ //10meter filter
            Log.d(TAG, "Accuracy is too low.");
            inaccurateLocationList.add(location);
            return false;
        }


        /* Kalman Filter */
        float Qvalue;

        long locationTimeInMillis = (long)(location.getElapsedRealtimeNanos() / 1000000);
        long elapsedTimeInMillis = locationTimeInMillis - runStartTimeInMillis;

        if(currentSpeed == 0.0f){
            Qvalue = 3.0f; //3 meters per second
        }else{
            Qvalue = currentSpeed; // meters per second
        }

        kalmanFilter.Process(location.getLatitude(), location.getLongitude(), location.getAccuracy(), elapsedTimeInMillis, Qvalue);
        double predictedLat = kalmanFilter.get_lat();
        double predictedLng = kalmanFilter.get_lng();

        Location predictedLocation = new Location("");//provider name is unecessary
        predictedLocation.setLatitude(predictedLat);//your coords of course
        predictedLocation.setLongitude(predictedLng);
        float predictedDeltaInMeters =  predictedLocation.distanceTo(location);

        if(predictedDeltaInMeters > 60){
            Log.d(TAG, "Kalman Filter detects mal GPS, we should probably remove this from track");
            kalmanFilter.consecutiveRejectCount += 1;

            if(kalmanFilter.consecutiveRejectCount > 3){
                kalmanFilter = new KalmanLatLong(3); //reset Kalman Filter if it rejects more than 3 times in raw.
            }

            kalmanNGLocationList.add(location);
            return false;
        }else{
            kalmanFilter.consecutiveRejectCount = 0;
        }

        /* Notifiy predicted location to UI */
        Intent intent = new Intent("PredictLocation");
        intent.putExtra("location", predictedLocation);
        LocalBroadcastManager.getInstance(this.getApplication()).sendBroadcast(intent);

        Log.d(TAG, "Location quality is good enough.");
        currentSpeed = location.getSpeed();
        locationList.add(location);


        return true;
    }
 
Example 19
Source File: DeviceLocation.java    From ARCore-Location with MIT License 4 votes vote down vote up
private boolean filterAndAddLocation(Location location) {

        if (currentBestLocation == null) {
            currentBestLocation = location;

            locationEvents();
        }

        long age = getLocationAge(location);

        if (age > 5 * 1000) { //more than 5 seconds
            Log.d(TAG, "Location is old");
            oldLocationList.add(location);

            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: old", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (location.getAccuracy() <= 0) {
            Log.d(TAG, "Latitidue and longitude values are invalid.");
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: invalid", Toast.LENGTH_SHORT).show();
            noAccuracyLocationList.add(location);
            return false;
        }

        //setAccuracy(newLocation.getAccuracy());
        float horizontalAccuracy = location.getAccuracy();
        if (horizontalAccuracy > getMinimumAccuracy()) { //10meter filter
            Log.d(TAG, "Accuracy is too low.");
            inaccurateLocationList.add(location);
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: innacurate", Toast.LENGTH_SHORT).show();
            return false;
        }


        /* Kalman Filter */
        float Qvalue;

        long locationTimeInMillis = (long) (location.getElapsedRealtimeNanos() / 1000000);
        long elapsedTimeInMillis = locationTimeInMillis - runStartTimeInMillis;

        if (currentSpeed == 0.0f) {
            Qvalue = 3.0f; //3 meters per second
        } else {
            Qvalue = currentSpeed; // meters per second
        }

        kalmanFilter.Process(location.getLatitude(), location.getLongitude(), location.getAccuracy(), elapsedTimeInMillis, Qvalue);
        double predictedLat = kalmanFilter.get_lat();
        double predictedLng = kalmanFilter.get_lng();

        Location predictedLocation = new Location("");//provider name is unecessary
        predictedLocation.setLatitude(predictedLat);//your coords of course
        predictedLocation.setLongitude(predictedLng);
        float predictedDeltaInMeters = predictedLocation.distanceTo(location);

        if (predictedDeltaInMeters > 60) {
            Log.d(TAG, "Kalman Filter detects mal GPS, we should probably remove this from track");
            kalmanFilter.consecutiveRejectCount += 1;

            if (kalmanFilter.consecutiveRejectCount > 3) {
                kalmanFilter = new KalmanLatLong(3); //reset Kalman Filter if it rejects more than 3 times in raw.
            }

            kalmanNGLocationList.add(location);
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: kalman filter", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            kalmanFilter.consecutiveRejectCount = 0;
        }


        Log.d(TAG, "Location quality is good enough.");
        currentBestLocation = predictedLocation;
        currentSpeed = location.getSpeed();
        locationList.add(location);

        locationEvents();


        return true;
    }
 
Example 20
Source File: DistanceFilterLocationProvider.java    From background-geolocation-android with Apache License 2.0 4 votes vote down vote up
public void onLocationChanged(Location location) {
    logger.debug("Location change: {} isMoving={}", location.toString(), isMoving);

    if (!isMoving && !isAcquiringStationaryLocation && stationaryLocation==null) {
        // Perhaps our GPS signal was interupted, re-acquire a stationaryLocation now.
        setPace(false);
    }

    showDebugToast( "mv:" + isMoving + ",acy:" + location.getAccuracy() + ",v:" + location.getSpeed() + ",df:" + scaledDistanceFilter);

    if (isAcquiringStationaryLocation) {
        if (stationaryLocation == null || stationaryLocation.getAccuracy() > location.getAccuracy()) {
            stationaryLocation = location;
        }
        if (++locationAcquisitionAttempts == MAX_STATIONARY_ACQUISITION_ATTEMPTS) {
            isAcquiringStationaryLocation = false;
            startMonitoringStationaryRegion(stationaryLocation);
            handleStationary(stationaryLocation, stationaryRadius);
            return;
        } else {
            // Unacceptable stationary-location: bail-out and wait for another.
            playDebugTone(Tone.BEEP);
            return;
        }
    } else if (isAcquiringSpeed) {
        if (++locationAcquisitionAttempts == MAX_SPEED_ACQUISITION_ATTEMPTS) {
            // Got enough samples, assume we're confident in reported speed now.  Play "woohoo" sound.
            playDebugTone(Tone.DOODLY_DOO);
            isAcquiringSpeed = false;
            scaledDistanceFilter = calculateDistanceFilter(location.getSpeed());
            setPace(true);
        } else {
            playDebugTone(Tone.BEEP);
            return;
        }
    } else if (isMoving) {
        playDebugTone(Tone.BEEP);

        // Only reset stationaryAlarm when accurate speed is detected, prevents spurious locations from resetting when stopped.
        if ( (location.getSpeed() >= 1) && (location.getAccuracy() <= mConfig.getStationaryRadius()) ) {
            resetStationaryAlarm();
        }
        // Calculate latest distanceFilter, if it changed by 5 m/s, we'll reconfigure our pace.
        Integer newDistanceFilter = calculateDistanceFilter(location.getSpeed());
        if (newDistanceFilter != scaledDistanceFilter.intValue()) {
            logger.info("Updating distanceFilter: new={} old={}", newDistanceFilter, scaledDistanceFilter);
            scaledDistanceFilter = newDistanceFilter;
            setPace(true);
        }
        if (lastLocation != null && location.distanceTo(lastLocation) < mConfig.getDistanceFilter()) {
            return;
        }
    } else if (stationaryLocation != null) {
        return;
    }
    // Go ahead and cache, push to server
    lastLocation = location;
    handleLocation(location);
}