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

The following examples show how to use android.location.Location#getSpeed() . 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: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void injectBestLocation(Location location) {
    int gnssLocationFlags = LOCATION_HAS_LAT_LONG |
            (location.hasAltitude() ? LOCATION_HAS_ALTITUDE : 0) |
            (location.hasSpeed() ? LOCATION_HAS_SPEED : 0) |
            (location.hasBearing() ? LOCATION_HAS_BEARING : 0) |
            (location.hasAccuracy() ? LOCATION_HAS_HORIZONTAL_ACCURACY : 0) |
            (location.hasVerticalAccuracy() ? LOCATION_HAS_VERTICAL_ACCURACY : 0) |
            (location.hasSpeedAccuracy() ? LOCATION_HAS_SPEED_ACCURACY : 0) |
            (location.hasBearingAccuracy() ? LOCATION_HAS_BEARING_ACCURACY : 0);

    double latitudeDegrees = location.getLatitude();
    double longitudeDegrees = location.getLongitude();
    double altitudeMeters = location.getAltitude();
    float speedMetersPerSec = location.getSpeed();
    float bearingDegrees = location.getBearing();
    float horizontalAccuracyMeters = location.getAccuracy();
    float verticalAccuracyMeters = location.getVerticalAccuracyMeters();
    float speedAccuracyMetersPerSecond = location.getSpeedAccuracyMetersPerSecond();
    float bearingAccuracyDegrees = location.getBearingAccuracyDegrees();
    long timestamp = location.getTime();
    native_inject_best_location(gnssLocationFlags, latitudeDegrees, longitudeDegrees,
            altitudeMeters, speedMetersPerSec, bearingDegrees, horizontalAccuracyMeters,
            verticalAccuracyMeters, speedAccuracyMetersPerSecond, bearingAccuracyDegrees,
            timestamp);
}
 
Example 2
Source File: WearableMainActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
    if (locationResult == null) {
        return;
    }


    for (Location location : locationResult.getLocations()) {
        Log.d(TAG, "onLocationChanged() : " + location);


        if (mWaitingForGpsSignal) {
            mWaitingForGpsSignal = false;
            updateActivityViewsBasedOnLocationPermissions();
        }

        mSpeed = location.getSpeed() * MPH_IN_METERS_PER_SECOND;
        updateSpeedInViews();
        addLocationEntry(location.getLatitude(), location.getLongitude());
    }
}
 
Example 3
Source File: SampleHeadingCompassUp.java    From osmdroid with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (mMapView == null)
        return;

    gpsbearing = location.getBearing();
    gpsspeed = location.getSpeed();
    lat = (float) location.getLatitude();
    lon = (float) location.getLongitude();
    alt = (float) location.getAltitude(); //meters
    timeOfFix = location.getTime();


    //use gps bearing instead of the compass

    float t = (360 - gpsbearing - this.deviceOrientation);
    if (t < 0) {
        t += 360;
    }
    if (t > 360) {
        t -= 360;
    }
    //help smooth everything out
    t = (int) t;
    t = t / 5;
    t = (int) t;
    t = t * 5;

    if (gpsspeed >= 0.01) {
        mMapView.setMapOrientation(t);
        //otherwise let the compass take over
    }
    updateDisplay(location.getBearing(), true);

}
 
Example 4
Source File: BackgroundLocation.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
public static BackgroundLocation fromLocation(Location location) {
    BackgroundLocation l = new BackgroundLocation();

    l.provider = location.getProvider();
    l.latitude = location.getLatitude();
    l.longitude = location.getLongitude();
    l.time = location.getTime();
    l.accuracy = location.getAccuracy();
    l.speed = location.getSpeed();
    l.bearing = location.getBearing();
    l.altitude = location.getAltitude();
    l.hasAccuracy = location.hasAccuracy();
    l.hasAltitude = location.hasAltitude();
    l.hasSpeed = location.hasSpeed();
    l.hasBearing = location.hasBearing();
    l.extras = location.getExtras();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        l.elapsedRealtimeNanos = location.getElapsedRealtimeNanos();
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        l.setIsFromMockProvider(location.isFromMockProvider());
    }

    return l;
}
 
Example 5
Source File: LocationEntity.java    From background_location_updates with Apache License 2.0 6 votes vote down vote up
public static LocationEntity fromAndroidLocation(Location location) {
    Double vAcc = null, cAcc = null, speedAcc = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vAcc = (double) location.getVerticalAccuracyMeters();
        cAcc = (double) location.getBearingAccuracyDegrees();
        speedAcc = (double) location.getSpeedAccuracyMetersPerSecond();
    }

    return new LocationEntity(
            (double) location.getAccuracy(),
            vAcc,
            location.getLongitude(),
            location.getLatitude(),
            location.getAltitude(),
            (double )location.getSpeed(),
            location.getTime(),
            0,
            (double) location.getBearing(),
            cAcc,
            speedAcc,
            location.getProvider()
    );
}
 
Example 6
Source File: Sensors.java    From Multiwii-Remote with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {

	oldLocation = this.location;
	this.location = location;

	PhoneLatitude = location.getLatitude();
	PhoneLongitude = location.getLongitude();
	PhoneAltitude = location.getAltitude();
	PhoneSpeed = location.getSpeed() * 100f;
	PhoneAccuracy = location.getAccuracy() * 100f;

	//MapCurrentPosition = new LatLng(location.getLatitude(), location.getLongitude());

	geoField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(), Double.valueOf(location.getLongitude()).floatValue(), Double.valueOf(location.getAltitude()).floatValue(), System.currentTimeMillis());
	Declination = geoField.getDeclination();

	if (mGPSListener != null)
		mGPSListener.onSensorsStateGPSLocationChange();
}
 
Example 7
Source File: MovementSpeedService.java    From privacy-friendly-pedometer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the speed from current location object.
 * If location has speed, this one will be used else the speed will be calculated from current
 * and last position.
 */
private void calculateSpeed(Location location){
    double newTime= System.currentTimeMillis();
    double newLat = location.getLatitude();
    double newLon = location.getLongitude();
    if(location.hasSpeed()){
        Log.i(LOG_TAG, "Location has speed");
        speed = location.getSpeed();
    } else {
        Log.i(LOG_TAG, "Location has no speed");
        double distance = calculationBydistance(newLat,newLon,oldLat,oldLon);
        double timeDifferent = (newTime - curTime) / 1000; // seconds
        speed = (float) (distance / timeDifferent);
        curTime = newTime;
        oldLat = newLat;
        oldLon = newLon;
    }

    Intent localIntent = new Intent(BROADCAST_ACTION_SPEED_CHANGED)
            // Add new step count
            .putExtra(EXTENDED_DATA_CURRENT_SPEED, speed);
    // Broadcasts the Intent to receivers in this app.
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
    Log.i(LOG_TAG, "New speed is " + speed + "m/sec " + speed * 3.6 + "km/h" );
}
 
Example 8
Source File: WeathForceActivity.java    From osmdroid with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (mMapView == null)
        return;
    //after the first fix, schedule the task to change the icon
    //mMapView.getController().setExpectedCenter(new GeoPoint(location.getLatitude(), location.getLongitude()));
    mMapView.invalidate();
    gpsbearing = location.getBearing();
    gpsspeed = location.getSpeed();
    lat = (float) location.getLatitude();
    lon = (float) location.getLongitude();
    alt = (float) location.getAltitude(); //meters
    timeOfFix = location.getTime();
}
 
Example 9
Source File: GpsServices.java    From SpeedMeter with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    data = MainActivity.getData();
    if (data.isRunning()){
        currentLat = location.getLatitude();
        currentLon = location.getLongitude();

        if (data.isFirstTime()){
            lastLat = currentLat;
            lastLon = currentLon;
            data.setFirstTime(false);
        }

        lastlocation.setLatitude(lastLat);
        lastlocation.setLongitude(lastLon);
        double distance = lastlocation.distanceTo(location);

        if (location.getAccuracy() < distance){
            data.addDistance(distance);

            lastLat = currentLat;
            lastLon = currentLon;
        }

        if (location.hasSpeed()) {
            data.setCurSpeed(location.getSpeed() * 3.6);
            if(location.getSpeed() == 0){
                new isStillStopped().execute();
            }
        }
        data.update();
        updateNotification(true);
    }
}
 
Example 10
Source File: MeasurementParser.java    From TowerCollector with Mozilla Public License 2.0 5 votes vote down vote up
protected void updateMeasurementWithLocation(Measurement measurement, Location location) {
    measurement.setLatitude(location.getLatitude());
    measurement.setLongitude(location.getLongitude());
    measurement.setGpsAccuracy(location.getAccuracy());
    float speed = location.getSpeed();
    if (speed > MAX_REASONABLE_SPEED)
        speed = 0;
    measurement.setGpsSpeed(speed);
    measurement.setGpsBearing(location.getBearing());
    measurement.setGpsAltitude(location.getAltitude());
}
 
Example 11
Source File: GearService.java    From WheelLogAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onLocationChanged(Location location) {
        if(bHasSpeed = location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasAltitude = location.hasAltitude())
            mAltitude = location.getAltitude();
        if(location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasBearing = location.hasBearing())
            mBearing = location.getBearing();
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        mTime = location.getTime();
//        transmitMessage(); Me lo he llevado a la rutina que se ejecuta de forma temporizada
    }
 
Example 12
Source File: LocationSensor.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@Override
// This sets fields longitude, latitude, altitude, hasLocationData, and
// hasAltitude, then calls LocationSensor.LocationChanged(), all in the
// enclosing class LocationSensor.
public void onLocationChanged(final Location location) {
  lastLocation = location;
  longitude = location.getLongitude();
  latitude = location.getLatitude();
  speed = location.getSpeed();
  // If the current location doesn't have altitude information, the prior
  // altitude reading is retained.
  if (location.hasAltitude()) {
    hasAltitude = true;
    altitude = location.getAltitude();
  }

  // By default Location.latitude == Location.longitude == 0.
  // So we want to ignore that case rather than generating a changed event.
  if (longitude != UNKNOWN_VALUE || latitude != UNKNOWN_VALUE) {
    hasLocationData = true;
    final double argLatitude = latitude;
    final double argLongitude = longitude;
    final double argAltitude = altitude;
    final float argSpeed = speed;
    androidUIHandler.post(new Runnable() {
        @Override
        public void run() {
          LocationChanged(argLatitude, argLongitude, argAltitude, argSpeed);
          for (LocationSensorListener listener : listeners) {
            listener.onLocationChanged(location);
          }
        }
      });
  }
}
 
Example 13
Source File: OpenLocateLocation.java    From openlocate-android with MIT License 5 votes vote down vote up
LocationInfo(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    horizontalAccuracy = location.getAccuracy();
    timeStampSecs = TimeUnit.MILLISECONDS.toSeconds(location.getTime());
    speed = location.getSpeed();
    course = location.getBearing();
    altitude = location.getAltitude();

    if (Build.VERSION.SDK_INT >= 26) {
        verticalAccuracy = location.getVerticalAccuracyMeters();
    }
}
 
Example 14
Source File: TripStatisticsUpdater.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Adds a location. TODO: This assume location has a valid time.
 * 
 * @param location the location
 * @param minRecordingDistance the min recording distance
 * @param calculateCalorie true means calculate calorie
 * @param activityType the activity type of current track which is used to
 *          calculate calorie
 * @param weight the weight to calculate calorie which is used to calculate
 *          calorie
 */
public void addLocation(Location location, int minRecordingDistance,
    boolean calculateCalorie, ActivityType activityType, double weight) {
  // Always update time
  updateTime(location.getTime());
  if (!LocationUtils.isValidLocation(location)) {
    // Either pause or resume marker
    if (location.getLatitude() == PAUSE_LATITUDE) {
      if (lastLocation != null && lastMovingLocation != null
          && lastLocation != lastMovingLocation) {
        currentSegment.addTotalDistance(lastMovingLocation.distanceTo(lastLocation));
      }
      tripStatistics.merge(currentSegment);
    }
    currentSegment = init(location.getTime());
    lastLocation = null;
    lastMovingLocation = null;
    elevationBuffer.reset();
    runBuffer.reset();
    gradeBuffer.reset();
    speedBuffer.reset();
    return;
  }
  currentSegment.updateLatitudeExtremities(location.getLatitude());
  currentSegment.updateLongitudeExtremities(location.getLongitude());

  double elevationDifference = location.hasAltitude() ? updateElevation(location.getAltitude())
      : 0.0;

  if (lastLocation == null || lastMovingLocation == null) {
    lastLocation = location;
    lastMovingLocation = location;
    return;
  }

  double movingDistance = lastMovingLocation.distanceTo(location);
  if (movingDistance < minRecordingDistance
      && (!location.hasSpeed() || location.getSpeed() < MAX_NO_MOVEMENT_SPEED)) {
    speedBuffer.reset();
    lastLocation = location;
    return;
  }
  long movingTime = location.getTime() - lastLocation.getTime();
  if (movingTime < 0) {
    lastLocation = location;
    return;
  }

  // Update total distance
  currentSegment.addTotalDistance(movingDistance);

  // Update moving time
  currentSegment.addMovingTime(movingTime);

  // Update grade
  double run = lastLocation.distanceTo(location);
  updateGrade(run, elevationDifference);

  // Update max speed
  if (location.hasSpeed() && lastLocation.hasSpeed()) {
    updateSpeed(
        location.getTime(), location.getSpeed(), lastLocation.getTime(), lastLocation.getSpeed());
  }
  
  if (calculateCalorie) {
    // Update calorie
    double calorie = CalorieUtils.getCalorie(lastMovingLocation, location,
        gradeBuffer.getAverage(), weight, activityType);
    currentSegment.addCalorie(calorie);
  }
  lastLocation = location;
  lastMovingLocation = location;
}
 
Example 15
Source File: StatsUtils.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the location values.
 * 
 * @param context the context
 * @param activity the activity for finding views. If null, the view cannot be
 *          null
 * @param view the containing view for finding views. If null, the activity
 *          cannot be null
 * @param location the location
 * @param isRecording true if recording
 */
public static void setLocationValues(
    Context context, Activity activity, View view, Location location, boolean isRecording) {
  boolean metricUnits = PreferencesUtils.isMetricUnits(context);
  boolean reportSpeed = PreferencesUtils.isReportSpeed(context);

  // Set speed/pace
  View speed = getView(activity, view, R.id.stats_speed);
  speed.setVisibility(isRecording ? View.VISIBLE : View.INVISIBLE);

  if (isRecording) {
    double value = isRecording && location != null && location.hasSpeed() ? location.getSpeed()
        : Double.NaN;
    setSpeed(context, speed, R.string.stats_speed, R.string.stats_pace, value, metricUnits,
        reportSpeed);
  }

  // Set elevation
  boolean showGradeElevation = PreferencesUtils.getBoolean(
      context, R.string.stats_show_grade_elevation_key,
      PreferencesUtils.STATS_SHOW_GRADE_ELEVATION_DEFAULT) && isRecording;
  View elevation = getView(activity, view, R.id.stats_elevation);
  elevation.setVisibility(showGradeElevation ? View.VISIBLE : View.GONE);

  if (showGradeElevation) {
    double altitude = location != null && location.hasAltitude() ? location.getAltitude()
        : Double.NaN;
    setElevationValue(context, elevation, -1, altitude, metricUnits);
  }

  // Set coordinate
  boolean showCoordinate = PreferencesUtils.getBoolean(
      context, R.string.stats_show_coordinate_key, PreferencesUtils.STATS_SHOW_COORDINATE_DEFAULT)
      && isRecording;
  View coordinateSeparator = getView(activity, view, R.id.stats_coordinate_separator);
  View coordinateContainer = getView(activity, view, R.id.stats_coordinate_container);

  if (coordinateSeparator != null) {
    coordinateSeparator.setVisibility(showCoordinate ? View.VISIBLE : View.GONE);
  }
  coordinateContainer.setVisibility(showCoordinate ? View.VISIBLE : View.GONE);

  if (showCoordinate) {
    double latitude = location != null ? location.getLatitude() : Double.NaN;
    double longitude = location != null ? location.getLongitude() : Double.NaN;
    setCoordinateValue(
        context, getView(activity, view, R.id.stats_latitude), R.string.stats_latitude, latitude);
    setCoordinateValue(context, getView(activity, view, R.id.stats_longitude),
        R.string.stats_longitude, longitude);
  }
}
 
Example 16
Source File: MapOverlay.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor for a potentially valid cached location.
 */
public CachedLocation(Location location) {
  this.valid = LocationUtils.isValidLocation(location);
  this.latLng = valid ? new LatLng(location.getLatitude(), location.getLongitude()) : null;
  this.speed = location.hasSpeed() ? location.getSpeed() * UnitConversions.MS_TO_KMH : -1.0;
}
 
Example 17
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 18
Source File: GPSTesterActivityController.java    From android-gps-test-tool with Apache License 2.0 4 votes vote down vote up
private static void writeResultToTable(
			Location location,
			LocationManager locationManager,
			String elapsedTimeGPSProvider,
			Boolean isNetworkAvailable){
		
    	_gpsLatitude = location.getLatitude();
    	_gpsLongitude = location.getLongitude();
    	_gpsAccuracy = location.getAccuracy();  
    	final double speed = location.getSpeed();
    	final double altitude = location.getAltitude();

    	String bestAvailableText = "";
    	
		boolean networkProviderEnabled = false; 	
		boolean gpsProviderEnabled = false;
		
		try{
			networkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
			gpsProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		}
		catch(Exception exc){
			Log.d("GPSTester","WriteResultToTable(): " + exc.getMessage());
		}

    	if(_networkAccuracy > _gpsAccuracy && _gpsAccuracy > 0.0 && gpsProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.GPS;
    		bestAvailableText = "<b><font color='yellow'>Best Accuracy</font> = <font color='red'>GPS</b></font>" +
    				"<br><b>GPS Accuracy:</b> " + DECIMAL_FORMAT_4.format(_gpsAccuracy) + " meters" +
    				"<br><b>GPS Lat/Lon:</b> " + _gpsLatitude + ", " + _gpsLongitude;
    	}  	
    	else if(_gpsAccuracy > _networkAccuracy && _networkAccuracy > 0.0 && networkProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.NETWORK;	    		
    		bestAvailableText = "<b><font color='yellow'><b><font color='yellow'>Best Accuracy</font> = <font color='red'>Network</b></font></b></font>" +
    				"<br><b>Network Accuracy:<b/> " + DECIMAL_FORMAT_4.format(_networkAccuracy) + " meters" +
    				"<br><b>Network Lat/Lon:<b/> " + _networkLatitude + ", " + _networkLongitude;
    	}
    	else if(_gpsAccuracy == 0.0 && _networkAccuracy > 0.0 && networkProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.NETWORK;	    		
    		bestAvailableText = "<b><font color='yellow'><b><font color='yellow'>Best Accuracy</font> = <font color='red'>Network</b></font></b></font>" +
    				"<br><b>Network Accuracy:<b/> " + DECIMAL_FORMAT_4.format(_networkAccuracy) + " meters" +
    				"<br><b>Network Lat/Lon:<b/> " + _networkLatitude + ", " + _networkLongitude;    		
    	}
    	else if(_networkAccuracy == 0.0 && _gpsAccuracy > 0.0 && gpsProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.GPS;
    		bestAvailableText = "<b><font color='yellow'>Best Accuracy</font> = <font color='red'>GPS</b></font>" +
    				"<br><b>GPS Accuracy:</b> " + DECIMAL_FORMAT_4.format(_gpsAccuracy) + " meters" +
    				"<br><b>GPS Lat/Lon:</b> " + _gpsLatitude + ", " + _gpsLongitude;    		
    	}
    	else{
    		_bestAvailableType = BestAvailableType.NULL;
    		bestAvailableText = "<b><font color='yellow'>Best Accuracy = N/A</b></font>" + 
    				"<br><b>Lat/Lon:</b> N/A" +  
    				"<br><b>Accuracy:</b> N/A";	    		
    	}
    	
	  	setBestAvailableImageView(_bestAvailableType);
		
		String elapsedTimeSinceLastGPS = _elapsedTimer.calculateTimeDifference(_initialGPSTime, _elapsedTimer.getElapsedtime());			  	
    	_initialGPSTime = _elapsedTimer.getElapsedtime();		
    	
	  	final String gpsLocationText = "<b><font color='yellow'>GPS Provider</b></font>" +
    		  	"<br><b>Timestamp:</b> " + _elapsedTimer.convertMillisToMDYHMSS(location.getTime()) +
				"<br><b>1st update elapsed time:</b> " + elapsedTimeGPSProvider +
			  	"<br><b>Since last update:</b> " + elapsedTimeSinceLastGPS +
		  		"<br><b>Lat/Lon:</b> " + _gpsLatitude + ", " + _gpsLongitude +
		  		"<br><b>DMSS:</b> " + 
		  			Location.convert(_gpsLatitude, Location.FORMAT_SECONDS) + ", " +					  			
		  			Location.convert(_gpsLongitude, Location.FORMAT_SECONDS) +
		  		"<br><b>Accuracy:</b> " + DECIMAL_FORMAT_4.format(_gpsAccuracy) + " meters" +
		  		"<br><b>Speed:</b> " + DECIMAL_FORMAT.format((speed * 2.2369)) + " mph" + ", " +
		  		DECIMAL_FORMAT.format(((speed * 3600)/1000)) + " km/h" +
		  		"<br><b>Altitude:</b> " + DECIMAL_FORMAT.format(altitude) + " m, " +
		  		DECIMAL_FORMAT.format(altitude * 3.2808) + " ft" +
		  		"<br><b>Bearing:</b> " + location.getBearing() + " deg";				  	
			  	
    	
	  	_gpsLocationTextView.setText(Html.fromHtml(gpsLocationText));	  	
    	_bestAvailableInfoTextView.setText(Html.fromHtml(bestAvailableText));
    	    	
    	//If true then we can draw on the map. Offline maps not available in this version
    	if(isNetworkAvailable == true){
			final int redMapGraphicSize = Integer.valueOf(_preferences.getString("pref_key_gpsGraphicSize", "10"));    	
	    	
	    	// Called when a new location is found by the network location provider.
	    	if(_preferences.getBoolean("pref_key_centerOnGPSCoords", true) == true){
	    		_map.centerAt(_gpsLatitude, _gpsLongitude, true);
	    	}
	    	if(_preferences.getBoolean("pref_key_accumulateMapPoints", true) == false){
//	    		_map.clearPointsGraphicLayer();
	    		_graphicsLayer.removeAll();
	    	}
	    	
	    	addGraphicLatLon(_gpsLatitude, _gpsLongitude, null, SimpleMarkerSymbol.STYLE.CIRCLE,Color.RED,redMapGraphicSize,_graphicsLayer,_map);
    	}
	}
 
Example 19
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);
}
 
Example 20
Source File: MapView.java    From Androzic with GNU General Public License v3.0 4 votes vote down vote up
public void setLocation(Location loc)
{
	currentViewport.bearing = loc.getBearing();
	currentViewport.speed = loc.getSpeed();

	currentViewport.location[0] = loc.getLatitude();
	currentViewport.location[1] = loc.getLongitude();
	application.getXYbyLatLon(currentViewport.location[0], currentViewport.location[1], currentViewport.locationXY);

	float turn = lookAheadB - currentViewport.bearing;
	if (Math.abs(turn) > 180)
	{
		turn = turn - Math.signum(turn) * 360;
	}
	if (Math.abs(turn) > 10)
		lookAheadB = currentViewport.bearing;

	if (mapRotate && isFollowing)
	{
		turn = currentViewport.mapHeading - currentViewport.bearing;
		if (Math.abs(turn) > 180)
		{
			turn = turn - Math.signum(turn) * 360;
		}
		if (Math.abs(turn) > 10)
		{
			currentViewport.mapHeading = currentViewport.bearing;
			refreshBuffer();
		}

		lookAheadB = 0;
	}

	long lastLocationMillis = loc.getTime();

	if (isFollowing)
	{
		boolean newMap;
		if (bestMapEnabled && bestMapInterval > 0 && lastLocationMillis - lastBestMap >= bestMapInterval)
		{
			newMap = application.setMapCenter(currentViewport.location[0], currentViewport.location[1], true, false, loadBestMap);
			lastBestMap = lastLocationMillis;
		}
		else
		{
			newMap = application.setMapCenter(currentViewport.location[0], currentViewport.location[1], true, false, false);
			if (newMap)
				loadBestMap = bestMapEnabled;
		}
		if (newMap)
			updateMapInfo();
		updateMapCenter();
	}
	calculateVectorLength();
}