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

The following examples show how to use android.location.Location#hasAltitude() . 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: WifiLocationDatabase.java    From AppleWifiNlpBackend with Apache License 2.0 6 votes vote down vote up
public void put(Location location) {
    if (location == null) return;
    ContentValues values = new ContentValues();
    values.put(FIELD_MAC, location.getExtras().getString(LocationRetriever
            .EXTRA_MAC_ADDRESS));
    values.put(FIELD_LATITUDE, location.getLatitude());
    values.put(FIELD_LONGITUDE, location.getLongitude());
    if (location.hasAltitude()) {
        values.put(FIELD_ALTITUDE, location.getAltitude());
    }
    if (location.hasAccuracy()) {
        values.put(FIELD_ACCURACY, location.getAccuracy());
    }
    values.put(FIELD_TIME, location.getTime());
    values.put(FIELD_VERIFIED, location.getExtras().getLong(LocationRetriever
            .EXTRA_VERIFIED_TIME));
    db.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
 
Example 2
Source File: ExifUtil.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the given location to the EXIF object.
 *
 * @param location The location to add.
 */
public void addLocationToExif(Location location)
{
    final Long ALTITUDE_PRECISION = 1L; // GPS altitude isn't particularly accurate (determined empirically)

    mExif.addGpsTags(location.getLatitude(), location.getLongitude());
    mExif.addGpsDateTimeStampTag(location.getTime());

    if (location.hasAltitude())
    {
        double altitude = location.getAltitude();
        addExifTag(ExifInterface.TAG_GPS_ALTITUDE, rational(altitude, ALTITUDE_PRECISION));
        short altitudeRef = altitude < 0 ? ExifInterface.GpsAltitudeRef.SEA_LEVEL_NEGATIVE
                : ExifInterface.GpsAltitudeRef.SEA_LEVEL;
        addExifTag(ExifInterface.TAG_GPS_ALTITUDE_REF, altitudeRef);
    }
}
 
Example 3
Source File: GpxTrackWriter.java    From mytracks with Apache License 2.0 6 votes vote down vote up
@Override
public void writeWaypoint(Waypoint waypoint) {
  if (printWriter != null) {
    Location location = waypoint.getLocation();
    if (location != null) {
      printWriter.println("<wpt " + formatLocation(location) + ">");
      if (location.hasAltitude()) {
        printWriter.println("<ele>" + ELEVATION_FORMAT.format(location.getAltitude()) + "</ele>");
      }
      printWriter.println(
          "<time>" + StringUtils.formatDateTimeIso8601(location.getTime()) + "</time>");
      printWriter.println("<name>" + StringUtils.formatCData(waypoint.getName()) + "</name>");
      printWriter.println("<cmt>" + StringUtils.formatCData(waypoint.getType().name()) + "</cmt>");
      printWriter.println(
          "<desc>" + StringUtils.formatCData(waypoint.getDescription()) + "</desc>");
      printWriter.println("<type>" + StringUtils.formatCData(waypoint.getCategory()) + "</type>");
      printWriter.println("</wpt>");
    }
  }
}
 
Example 4
Source File: DatabaseHelper.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
private ContentValues getLifelineLocation(long id, String name, Location location) throws JSONException {
    JSONObject jloc = new JSONObject();
    if (name != null)
        jloc.put("name", name);
    jloc.put("lat", location.getLatitude());
    jloc.put("lon", location.getLongitude());
    if (location.hasAltitude())
        jloc.put("alt", Math.round(location.getAltitude()));
    if (location.hasAccuracy())
        jloc.put("acc", Math.round(location.getAccuracy()));

    ContentValues cv = new ContentValues();
    cv.put("time", location.getTime());
    cv.put("source", mContext.getPackageName());
    cv.put("type", name == null ? "trackpoint" : "waypoint");
    cv.put("data", jloc.toString());
    cv.put("reference", Long.toString(id));
    return cv;
}
 
Example 5
Source File: LocationService.java    From FineGeotag with GNU General Public License v3.0 6 votes vote down vote up
public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jObject = new JsonObject();

    jObject.addProperty("Provider", src.getProvider());
    jObject.addProperty("Time", src.getTime());
    jObject.addProperty("Latitude", src.getLatitude());
    jObject.addProperty("Longitude", src.getLongitude());

    if (src.hasAltitude())
        jObject.addProperty("Altitude", src.getAltitude());

    if (src.hasSpeed())
        jObject.addProperty("Speed", src.getSpeed());

    if (src.hasAccuracy())
        jObject.addProperty("Accuracy", src.getAccuracy());

    if (src.hasBearing())
        jObject.addProperty("Bearing", src.getBearing());

    return jObject;
}
 
Example 6
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 7
Source File: ExifInterfaceEx.java    From FineGeotag with GNU General Public License v3.0 5 votes vote down vote up
public void setLocation(Location location) {
    // Latitude
    double lat = location.getLatitude();
    this.setAttribute(TAG_GPS_LATITUDE_REF, lat > 0 ? "N" : "S");
    this.setAttribute(TAG_GPS_LATITUDE, DMS(lat));

    // Longitude
    double lon = location.getLongitude();
    this.setAttribute(TAG_GPS_LONGITUDE_REF, lon > 0 ? "E" : "W");
    this.setAttribute(TAG_GPS_LONGITUDE, DMS(lon));

    // Date/time
    Date date = new Date(location.getTime());
    this.setAttribute(TAG_GPS_DATESTAMP, new SimpleDateFormat("y:M:d").format(date));
    this.setAttribute(TAG_GPS_TIMESTAMP, new SimpleDateFormat("H:m:s").format(date));

    // Altitude
    if (location.hasAltitude()) {
        double altitude = location.getAltitude();
        this.setAttribute(TAG_GPS_ALTITUDE_REF, altitude > 0 ? "0" : "1");
        this.setAttribute(TAG_GPS_ALTITUDE, String.valueOf(Math.abs(altitude)));
    }

    // Speed
    if (location.hasSpeed()) {
        this.setAttribute("GPSSpeedRef", "K"); // Km/h
        this.setAttribute("GPSSpeed", String.valueOf(location.getSpeed() * 3600 / 1000));
    }
}
 
Example 8
Source File: KmlTrackWriter.java    From mytracks with Apache License 2.0 5 votes vote down vote up
private String getCoordinates(Location location, String separator) {
  StringBuffer buffer = new StringBuffer();
  buffer.append(location.getLongitude() + separator + location.getLatitude());
  if (location.hasAltitude()) {
    buffer.append(separator + location.getAltitude());
  }
  return buffer.toString();    
}
 
Example 9
Source File: Util.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static double distance(Location lastLocation, Location location) {
    if (lastLocation.hasAltitude() && location.hasAltitude())
        // Pythagoras
        return Math.sqrt(
                Math.pow(lastLocation.distanceTo(location), 2) +
                        Math.pow(Math.abs(lastLocation.getAltitude() - location.getAltitude()), 2));
    else
        return lastLocation.distanceTo(location);
}
 
Example 10
Source File: MyTracksProviderUtilsImpl.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the {@link ContentValues} for a {@link Location}.
 * 
 * @param location the location
 * @param trackId the track id
 */
private ContentValues createContentValues(Location location, long trackId) {
  ContentValues values = new ContentValues();
  values.put(TrackPointsColumns.TRACKID, trackId);
  values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6));
  values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6));

  // Hack for Samsung phones that don't properly populate the time field
  long time = location.getTime();
  if (time == 0) {
    time = System.currentTimeMillis();
  }
  values.put(TrackPointsColumns.TIME, time);
  if (location.hasAltitude()) {
    values.put(TrackPointsColumns.ALTITUDE, location.getAltitude());
  }
  if (location.hasAccuracy()) {
    values.put(TrackPointsColumns.ACCURACY, location.getAccuracy());
  }
  if (location.hasSpeed()) {
    values.put(TrackPointsColumns.SPEED, location.getSpeed());
  }
  if (location.hasBearing()) {
    values.put(TrackPointsColumns.BEARING, location.getBearing());
  }

  if (location instanceof MyTracksLocation) {
    MyTracksLocation myTracksLocation = (MyTracksLocation) location;
    if (myTracksLocation.getSensorDataSet() != null) {
      values.put(TrackPointsColumns.SENSOR, myTracksLocation.getSensorDataSet().toByteArray());
    }
  }
  return values;
}
 
Example 11
Source File: LocationService.java    From FineGeotag with GNU General Public License v3.0 5 votes vote down vote up
private boolean isBetterLocation(Location prev, Location current) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean pref_altitude = prefs.getBoolean(ActivitySettings.PREF_ALTITUDE, ActivitySettings.DEFAULT_ALTITUDE);
    return (prev == null ||
            ((!pref_altitude || !prev.hasAltitude() || current.hasAltitude()) &&
                    (current.hasAccuracy() ? current.getAccuracy() : Float.MAX_VALUE) <
                            (prev.hasAccuracy() ? prev.getAccuracy() : Float.MAX_VALUE)));
}
 
Example 12
Source File: Kalman.java    From DejaVu with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void update(Location location) {
    if (location == null)
        return;

    // Reusable
    final double accuracy = location.getAccuracy();
    double position, noise;
    long timeMs = location.getTime();

    predict(timeMs);
    mTimeOfUpdate = timeMs;
    samples++;

    // Latitude
    position = location.getLatitude();
    noise = accuracy * BackendService.METER_TO_DEG;
    mLatTracker.update(position, noise);

    // Longitude
    position = location.getLongitude();
    noise = accuracy * Math.cos(Math.toRadians(location.getLatitude())) * BackendService.METER_TO_DEG ;
    mLonTracker.update(position, noise);

    // Altitude
    if (location.hasAltitude()) {
        position = location.getAltitude();
        noise = accuracy;
        if (mAltTracker == null) {
            mAltTracker = new Kalman1Dim(ALTITUDE_NOISE, timeMs);
            mAltTracker.setState(position, 0.0, noise);
        } else {
            mAltTracker.update(position, noise);
        }
    }
}
 
Example 13
Source File: LocationHelper.java    From ActivityDiary with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Called when the location has changed.
 * <p>
 * <p> There are no restrictions on the use of the supplied Location object.
 *
 * @param location The new location, as a Location object.
 */
@Override
public void onLocationChanged(Location location) {
    ContentValues values = new ContentValues();
    currentLocation = location;
    values.put(ActivityDiaryContract.DiaryLocation.TIMESTAMP, location.getTime());
    values.put(ActivityDiaryContract.DiaryLocation.LATITUDE, location.getLatitude());
    values.put(ActivityDiaryContract.DiaryLocation.LONGITUDE, location.getLongitude());
    if (location.hasAccuracy()) {
        values.put(ActivityDiaryContract.DiaryLocation.HACC, new Integer(Math.round(location.getAccuracy() * 10)));
    }
    if (location.hasSpeed()) {
        values.put(ActivityDiaryContract.DiaryLocation.SPEED, location.getSpeed());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (location.hasSpeedAccuracy()) {
                values.put(ActivityDiaryContract.DiaryLocation.SACC, new Integer(Math.round(location.getSpeedAccuracyMetersPerSecond() * 10)));
            }
        }
    }
    if (location.hasAltitude()) {
        values.put(ActivityDiaryContract.DiaryLocation.ALTITUDE, location.getAltitude());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (location.hasVerticalAccuracy()) {
                values.put(ActivityDiaryContract.DiaryLocation.VACC,  new Integer(Math.round(location.getVerticalAccuracyMeters() * 10)));
            }
        }
    }
    startInsert(0, null, ActivityDiaryContract.DiaryLocation.CONTENT_URI,
            values);

}
 
Example 14
Source File: GpsSearch.java    From Finder with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (no_accurate_coords && location.hasAccuracy() &&
            (location.getAccuracy() < Float.valueOf(sPref.getString(GPS_ACCURACY, GPS_ACCURACY_DEFAULT)))) {
        locMan.removeUpdates(locListen);  //will be disabled after first accurate coords
        sms_answer.append("lat:");
        sms_answer.append(String.format(Locale.US, "%.8f",location.getLatitude()));
        sms_answer.append(" ");
        sms_answer.append("lon:");
        sms_answer.append(String.format(Locale.US, "%.8f", location.getLongitude()));
        sms_answer.append(" ");
        if (location.hasAltitude()) {
            sms_answer.append("alt:");
            sms_answer.append(String.format(Locale.US, "%.0f", location.getAltitude()));
            sms_answer.append(" m ");
        }
        if (location.hasSpeed()) {
            sms_answer.append("vel:");
            sms_answer.append(String.format(Locale.US, "%.2f", location.getSpeed() * 3.6f));
            sms_answer.append(" km/h ");
        }
        if (location.hasBearing()) {
            sms_answer.append("az:");
            sms_answer.append(String.format(Locale.US, "%.0f", location.getBearing()));
            sms_answer.append(" ");
        }
        sms_answer.append("acc:");
        sms_answer.append(String.format(Locale.US, "%.0f", location.getAccuracy()));
        sms_answer.append("\n");
        sms_answer.append(gen_short_osm_url(location.getLatitude(), location.getLongitude(), OSM_ZOOM));
        sms_answer.append("\n");
        no_accurate_coords = false;
        start_send();
    } else {
        lastTrue = true;  //coords are ready but not enough precise, send them
        lastLocation = location;
    }
}
 
Example 15
Source File: InformationCollector.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
public static JSONObject fillBasicInfo(JSONObject object, Context ctx) throws JSONException
{
    object.put("plattform", PLATTFORM_NAME);
    object.put("os_version", android.os.Build.VERSION.RELEASE + "(" + android.os.Build.VERSION.INCREMENTAL
            + ")");
    object.put("api_level", String.valueOf(android.os.Build.VERSION.SDK_INT));
    object.put("device", android.os.Build.DEVICE);
    object.put("model", android.os.Build.MODEL);
    object.put("product", android.os.Build.PRODUCT);
    object.put("language", Locale.getDefault().getLanguage());
    object.put("timezone", TimeZone.getDefault().getID());
    object.put("softwareRevision", RevisionHelper.getVerboseRevision());
    PackageInfo pInfo = getPackageInfo(ctx);
    if (pInfo != null)
    {
        object.put("softwareVersionCode", pInfo.versionCode);
        object.put("softwareVersionName", pInfo.versionName);
    }
    object.put("type", at.alladin.rmbt.android.util.Config.RMBT_CLIENT_TYPE);
    
    addClientFeatures(object, ctx);
    
    if (BASIC_INFORMATION_INCLUDE_LOCATION) {
     Location loc = GeoLocation.getLastKnownLocation(ctx);
     if (loc != null) {
     JSONObject locationJson = new JSONObject();
      locationJson.put("lat", loc.getLatitude());
      locationJson.put("long", loc.getLongitude());
      locationJson.put("provider", loc.getProvider());
      if (loc.hasSpeed())
      	locationJson.put("speed", loc.getSpeed());
      if (loc.hasAltitude())
      	locationJson.put("altitude", loc.getAltitude());
      locationJson.put("age", System.currentTimeMillis() - loc.getTime()); //getElapsedRealtimeNanos() would be better, but require higher API-level
      if (loc.hasAccuracy())
      	locationJson.put("accuracy", loc.getAccuracy());
      if (loc.hasSpeed())
      	locationJson.put("speed", loc.getSpeed());
      /*
       *  would require API level 18
      if (loc.isFromMockProvider())
      	locationJson.put("mock",loc.isFromMockProvider());
      */
      object.put("location", locationJson);
     }
    }
    
    InformationCollector infoCollector = null;
    
    if (ctx instanceof RMBTMainActivity) {
    	Fragment curFragment = ((RMBTMainActivity) ctx).getCurrentFragment();
        if (curFragment != null) {
     	if (curFragment instanceof RMBTMainMenuFragment) {
     		infoCollector = ((RMBTMainMenuFragment) curFragment).getInformationCollector();
     	}
        }
    }

    if (BASIC_INFORMATION_INCLUDE_LAST_SIGNAL_ITEM && (infoCollector != null)) {
    	SignalItem signalItem = infoCollector.getLastSignalItem();
    	if (signalItem != null) {
    		object.put("last_signal_item", signalItem.toJson());
    	}
    	else {
    		object.put("last_signal_item", JSONObject.NULL);
    	}
    }

    return object;
}
 
Example 16
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 17
Source File: TcxTrackWriter.java    From mytracks with Apache License 2.0 4 votes vote down vote up
@Override
public void writeLocation(Location location) {
  if (printWriter != null) {
    printWriter.println("<Trackpoint>");
    printWriter.println("<Time>" + StringUtils.formatDateTimeIso8601(location.getTime()) + "</Time>");
    printWriter.println("<Position>");
    printWriter.println("<LatitudeDegrees>" + location.getLatitude() + "</LatitudeDegrees>");
    printWriter.println("<LongitudeDegrees>" + location.getLongitude() + "</LongitudeDegrees>");
    printWriter.println("</Position>");
    if (location.hasAltitude()) {
      printWriter.println("<AltitudeMeters>" + location.getAltitude() + "</AltitudeMeters>");
    }

    if (location instanceof MyTracksLocation) {
      SensorDataSet sensorDataSet = ((MyTracksLocation) location).getSensorDataSet();
      if (sensorDataSet != null) {
        boolean heartRateAvailable = sensorDataSet.hasHeartRate()
            && sensorDataSet.getHeartRate().hasValue()
            && sensorDataSet.getHeartRate().getState() == Sensor.SensorState.SENDING;
        boolean cadenceAvailable = sensorDataSet.hasCadence()
          && sensorDataSet.getCadence().hasValue()
          && sensorDataSet.getCadence().getState() == Sensor.SensorState.SENDING;
        boolean powerAvailable = sensorDataSet.hasPower() 
          && sensorDataSet.getPower().hasValue()
          && sensorDataSet.getPower().getState() == Sensor.SensorState.SENDING;
        
        if (heartRateAvailable) {
          printWriter.println("<HeartRateBpm>");
          printWriter.println("<Value>" + sensorDataSet.getHeartRate().getValue() + "</Value>");
          printWriter.println("</HeartRateBpm>");
        }

        // <Cadence> needs to be put before <Extensions>.
        // According to the TCX spec, <Cadence> is only for the biking sport
        // type. For others, use <RunCadence> in <Extensions>.
        if (cadenceAvailable && sportType == SportType.BIKING) {
          // The spec requires the max value be 254.
          printWriter.println(
              "<Cadence>" + Math.min(254, sensorDataSet.getCadence().getValue()) + "</Cadence>");
        }

        if ((cadenceAvailable && sportType != SportType.BIKING) || powerAvailable) {
          printWriter.println("<Extensions>");
          printWriter.println(
              "<TPX xmlns=\"http://www.garmin.com/xmlschemas/ActivityExtension/v2\">");

          // <RunCadence> needs to be put before <Watts>.
          if (cadenceAvailable && sportType != SportType.BIKING) {
            // The spec requires the max value to be 254.
            printWriter.println("<RunCadence>"
                + Math.min(254, sensorDataSet.getCadence().getValue()) + "</RunCadence>");
          }

          if (powerAvailable) {
            printWriter.println("<Watts>" + sensorDataSet.getPower().getValue() + "</Watts>");
          }
          printWriter.println("</TPX>");
          printWriter.println("</Extensions>");
        }
      }
    }
    printWriter.println("</Trackpoint>");
  }
}
 
Example 18
Source File: CsvTrackWriter.java    From mytracks with Apache License 2.0 4 votes vote down vote up
private String getAltitude(Location location) {
  return location.hasAltitude() ? Double.toString(location.getAltitude()) : null;
}
 
Example 19
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
private void handlePassiveLocationUpdate(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Process passive location update
    Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
    Log.i(TAG, "Update passive location=" + location);
    if (location == null || (location.getLatitude() == 0.0 && location.getLongitude() == 0.0))
        return;

    // Filter inaccurate passive locations
    int pref_inaccurate = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_INACCURATE, SettingsFragment.DEFAULT_PASSIVE_INACCURATE));
    if (!location.hasAccuracy() || location.getAccuracy() > pref_inaccurate) {
        Log.i(TAG, "Filtering inaccurate passive location=" + location);
        return;
    }

    // Get last location
    Location lastLocation = LocationDeserializer.deserialize(prefs.getString(SettingsFragment.PREF_LAST_LOCATION, null));
    if (lastLocation == null) {
        Log.i(TAG, "Passive location without last location, location=" + location);
        return;
    }

    // Filter old locations
    if (location.getTime() <= lastLocation.getTime()) {
        Log.i(TAG, "Passive location is older than last location, location=" + location);
        return;
    }

    // Correct altitude
    correctAltitude(location, this);

    // Filter nearby passive locations
    int pref_nearby = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_NEARBY, SettingsFragment.DEFAULT_PASSIVE_NEARBY));
    if (Util.distance(lastLocation, location) < pref_nearby &&
            (lastLocation.hasAccuracy() ? lastLocation.getAccuracy() : Float.MAX_VALUE) <=
                    (location.hasAccuracy() ? location.getAccuracy() : Float.MAX_VALUE)) {
        Log.i(TAG, "Filtering nearby passive location=" + location);
        return;
    }

    float bchange = 0;
    double achange = 0;
    boolean update = false;

    // Handle bearing change
    if (location.hasBearing()) {
        int pref_bearing_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_BEARING, SettingsFragment.DEFAULT_PASSIVE_BEARING));
        bchange = Math.abs(lastLocation.getBearing() - location.getBearing());
        if (bchange > 180)
            bchange = 360 - bchange;
        if (!lastLocation.hasBearing() || bchange > pref_bearing_change) {
            Log.i(TAG, "Bearing changed to " + location.getBearing());
            update = true;
        }
    }

    // Handle altitude change
    if (location.hasAltitude()) {
        int pref_altitude_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_ALTITUDE, SettingsFragment.DEFAULT_PASSIVE_ALTITUDE));
        achange = Math.abs(lastLocation.getAltitude() - location.getAltitude());
        if (!lastLocation.hasAltitude() || achange > pref_altitude_change) {
            Log.i(TAG, "Altitude changed to " + location.getAltitude());
            update = true;
        }
    }

    if (update) {
        // Persist new location
        prefs.edit().putString(SettingsFragment.PREF_LAST_LOCATION, LocationSerializer.serialize(location)).apply();
        DatabaseHelper dh = null;
        try {
            dh = new DatabaseHelper(this);
            int altitude_type = (location.hasAltitude() ? ALTITUDE_GPS : ALTITUDE_NONE);
            dh.insertLocation(location, altitude_type, null).close();
        } finally {
            if (dh != null)
                dh.close();
        }

        // Feedback
        showStateNotification(this);
        if (Util.debugMode(this))
            Util.toast(getString(R.string.title_trackpoint) +
                    " " + getProviderName(location, this) +
                    " " + Math.round(bchange) +
                    "° / " + Math.round(achange) + "m", Toast.LENGTH_SHORT, this);
    }
}
 
Example 20
Source File: TelephonyHelper.java    From Local-GSM-Backend with Apache License 2.0 4 votes vote down vote up
public Location weightedAverage(String source, Collection<Location> locations) {
        Location rslt;

        if (locations == null || locations.size() == 0) {
            return null;
        }

        int num = locations.size();
        int totalWeight = 0;
        double latitude = 0;
        double longitude = 0;
        float accuracy = 0;
        int altitudes = 0;
        double altitude = 0;

        for (Location value : locations) {
            if (value != null) {
                // Create weight value based on accuracy. Higher accuracy
                // (lower tower radius/range) towers get higher weight.
                float thisAcc = value.getAccuracy();
                if (thisAcc < 1f)
                    thisAcc = 1f;

                int wgt = (int) (100000f / thisAcc);
                if (wgt < 1)
                    wgt = 1;

                latitude += (value.getLatitude() * wgt);
                longitude += (value.getLongitude() * wgt);
                accuracy += (value.getAccuracy() * wgt);
                totalWeight += wgt;

//                if (DEBUG) Log.i(TAG, "(lat="+ latitude + ", lng=" + longitude + ", acc=" + accuracy + ") / wgt=" + totalWeight );

                if (value.hasAltitude()) {
                    altitude += value.getAltitude();
                    altitudes++;
                }
            }
        }
        latitude = latitude / totalWeight;
        longitude = longitude / totalWeight;
        accuracy = accuracy / totalWeight;
        altitude = altitude / altitudes;
        Bundle extras = new Bundle();
        extras.putInt("AVERAGED_OF", num);
//        if (DEBUG) Log.i(TAG, "Location est (lat="+ latitude + ", lng=" + longitude + ", acc=" + accuracy);

        if (altitudes > 0) {
            rslt = LocationHelper.create(source,
                    latitude,
                    longitude,
                    altitude,
                    accuracy,
                    extras);
        } else {
            rslt = LocationHelper.create(source,
                    latitude,
                    longitude,
                    accuracy,
                    extras);
        }
        rslt.setTime(System.currentTimeMillis());
        return rslt;
    }