/**
   * 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;
  }
 @Override
 public void onLocationChanged(Location location) {
   Log.w(LOG, "############## onLocationChanged ...");
   if (this.location == null) {
     this.location = location;
   } else {
     Log.w(
         LOG,
         "Old Location lat: "
             + this.location.getLatitude()
             + " long: "
             + this.location.getLongitude()
             + " - accuracy: "
             + this.location.getAccuracy());
     if (location.getAccuracy() == ACCURAY_THRESHOLD
         || location.getAccuracy() < ACCURAY_THRESHOLD) {
       this.location = location;
       mLocationClient.removeLocationUpdates(this);
     }
   }
   Log.e(
       LOG,
       "++Location has changed to lat: "
           + location.getLatitude()
           + " long: "
           + location.getLongitude()
           + " - accuracy: "
           + location.getAccuracy());
 }
Exemplo n.º 3
0
  private boolean isBetterLocation(Location location, Location currentBest) {

    if (currentBest == null) {
      return true;
    }

    long timeDelta = location.getTime() - currentBest.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    if (isSignificantlyNewer) {
      return true;
    }
    if (isSignificantlyOlder) {
      return false;
    }

    int accDelta = (int) (location.getAccuracy() - currentBest.getAccuracy());
    boolean isMoreAccurate = accDelta < 0;
    boolean isMuchWorse = accDelta > 200;
    boolean sameProvider = isSameProvider(location.getProvider(), currentBest.getProvider());

    if (!isMoreAccurate) {
      // Less accurate
      return false;
    } else if (isNewer && isMoreAccurate) {
      return true;
    } else if (isNewer && !isMuchWorse && sameProvider) {
      return true;
    }
    return false;
  }
 public void onLocationChanged(Location location) {
   Log.d(
       MainFrame.TAG,
       "Normal Location Changed: "
           + location.getProvider()
           + " lat: "
           + location.getLatitude()
           + " lon: "
           + location.getLongitude()
           + " alt: "
           + location.getAltitude()
           + " acc: "
           + location.getAccuracy());
   try {
     addWalkingPathPosition(location);
     deleteAllDownloadActivity();
     Log.v(
         MainFrame.TAG,
         "Location Changed: "
             + location.getProvider()
             + " lat: "
             + location.getLatitude()
             + " lon: "
             + location.getLongitude()
             + " alt: "
             + location.getAltitude()
             + " acc: "
             + location.getAccuracy());
     myController.setPosition(location);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Exemplo n.º 5
0
  void gotoLastKnownPosition() {
    Location currentLocation;
    Location bestLocation = null;

    for (String provider : mLocationManager.getProviders(true)) {
      currentLocation = mLocationManager.getLastKnownLocation(provider);
      if (currentLocation == null) continue;
      if (bestLocation == null || currentLocation.getAccuracy() < bestLocation.getAccuracy()) {
        bestLocation = currentLocation;
      }
    }

    if (bestLocation != null) {
      MapPosition mapPosition = getLocation(bestLocation);

      mTileMap.setMapCenter(mapPosition);
      accuracy = bestLocation.getAccuracy();
      mLocation = bestLocation;
      mTileMap.mapActivity.invalidateMap();

    } else {
      // mTileMap.showToastOnUiThread(mTileMap
      // .getString(R.string.error_last_location_unknown));
    }
  }
Exemplo n.º 6
0
  public static Location GetLastKnownLocation(Context context) {
    // you might be tempted to use LocationManager.getBestProvider here instead
    // but beware, it is less likely to return a location than this strategy

    Location location = null, temp = null;
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = manager.getAllProviders();
    boolean enabled = false;

    // loop through location providers
    for (String provider : providers) {

      // if we've found an active provider and this one isn't, skip it
      if (enabled && !manager.isProviderEnabled(provider)) continue;

      // get the location from the provider
      temp = manager.getLastKnownLocation(provider);

      // if it's more accurate than what we've got, replace
      if (temp != null) {
        if (location == null || location.getAccuracy() < temp.getAccuracy()) {
          location = temp;
          enabled = manager.isProviderEnabled(provider);
        }
      }
    }
    return location;
  }
Exemplo n.º 7
0
  @Override
  public void onLocationChanged(Location location) {
    if (mRefreshLocation) {
      mLocation = location;
      if (mLocation != null) {
        // Bug report: cached GeoPoint is being returned as the first value.
        // Wait for the 2nd value to be returned, which is hopefully not cached?
        ++mLocationCount;
        InfoLogger.geolog(
            "GeoPointMapActivity: "
                + System.currentTimeMillis()
                + " onLocationChanged("
                + mLocationCount
                + ") lat: "
                + mLocation.getLatitude()
                + " long: "
                + mLocation.getLongitude()
                + " acc: "
                + mLocation.getAccuracy());

        if (mLocationCount > 1) {
          mLocationStatus.setText(
              getString(
                  R.string.location_provider_accuracy,
                  mLocation.getProvider(),
                  truncateFloat(mLocation.getAccuracy())));
          mLatLng = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
          if (!mZoomed) {
            mZoomed = true;
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
          } else {
            mMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng));
          }

          // create a marker on the map or move the existing marker to the
          // new location
          if (mMarker == null) {
            mMarkerOption.position(mLatLng);
            mMarker = mMap.addMarker(mMarkerOption);
            mShowLocation.setClickable(true);
          } else {
            mMarker.setPosition(mLatLng);
          }

          // If location is accurate enough, stop updating position and make the marker draggable
          if (mLocation.getAccuracy() <= mLocationAccuracy) {
            stopGeolocating();
          }
        }

      } else {
        InfoLogger.geolog(
            "GeoPointMapActivity: "
                + System.currentTimeMillis()
                + " onLocationChanged("
                + mLocationCount
                + ") null location");
      }
    }
  }
  /**
   * Determina se la nuova posizione rilevata &egrave; migliore dell'ultima.
   *
   * <p>L'implementazione segue l'algoritmo descritto nella documentazione Android per stimare la
   * posizione quando le rilevazioni provengono da pi&ugrave; provider con accuratezze diverse.
   *
   * @param location la nuova posizione da valutare
   * @param last l'ultima posizione rilevata
   * @see
   *     http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate
   * @author Michele Piccirillo <*****@*****.**>
   */
  public static boolean isBetterLocation(Location location, Location last) {
    if (location == null) return false;

    if (last == null) return true;

    long timeDelta = location.getTime() - last.getTime();

    // Se la rilevazione e' stata presa molto piu' di recente, viene considerata migliore
    if (timeDelta > Setup.TRACKING_TIME_WINDOW) return true;

    // Se e' molto piu' vecchia dell'ultima, viene scartata
    if (timeDelta < -Setup.TRACKING_TIME_WINDOW) return false;

    // Differenza di accuratezza tra vecchia e nuova posizione
    int accuracyDelta = (int) (location.getAccuracy() - last.getAccuracy());

    // L'ultima posizione e' piu' accurata
    if (accuracyDelta < 0) return true;

    // La posizione ha la stessa accuratezza ma e' piu' recente
    if (timeDelta > 0 && accuracyDelta == 0) return true;

    // Controlla se la vecchia e la nuova posizione provengono dallo stesso provider
    String provider1 = location.getProvider();
    String provider2 = location.getProvider();
    boolean isFromSameProvider =
        (provider1 == null && provider2 == null) || (provider1.equals(provider2));

    // La posizione e' piu' recente e viene dallo stesso provider
    // L'accuratezza e' inferiore ma entro un range accettabile
    if (timeDelta > 0 && accuracyDelta <= 200 && isFromSameProvider) return true;

    return false;
  }
Exemplo n.º 9
0
  @Override
  public void onLocationChanged(Location location) {
    Log.d(
        TAG,
        "Location changed: "
            + location.getProvider()
            + ", "
            + location.getLatitude()
            + ","
            + location.getLongitude());

    if (lastBestLocation == null) {
      lastBestLocation = location;
    } else {
      if (lastBestLocation.getAccuracy() > location.getAccuracy()) {
        lastBestLocation = location;
      }
    }

    if (location.getAccuracy() < ACCURACY_THRESHOLD) {
      stopGpsHandler.removeCallbacks(stopGpsSearch);
      locationManager.removeUpdates(AlarmReciever.this);
      // TODO addAndSendLocations(lastBestLocation,....);
    }
  }
  protected void drawMyLocation(
      final Canvas canvas,
      final MapView mapView,
      final Location lastFix,
      final GeoPoint myLocation) {

    final Projection pj = mapView.getProjection();
    pj.toMapPixels(mMyLocation, mMapCoords);

    if (mDrawAccuracyEnabled) {
      final float radius = pj.metersToEquatorPixels(lastFix.getAccuracy());

      mCirclePaint.setAlpha(50);
      mCirclePaint.setStyle(Style.FILL);
      canvas.drawCircle(mMapCoords.x, mMapCoords.y, radius, mCirclePaint);

      mCirclePaint.setAlpha(150);
      mCirclePaint.setStyle(Style.STROKE);
      canvas.drawCircle(mMapCoords.x, mMapCoords.y, radius, mCirclePaint);
    }

    canvas.getMatrix(mMatrix);
    mMatrix.getValues(mMatrixValues);

    if (DEBUGMODE) {
      final float tx = (-mMatrixValues[Matrix.MTRANS_X] + 20) / mMatrixValues[Matrix.MSCALE_X];
      final float ty = (-mMatrixValues[Matrix.MTRANS_Y] + 90) / mMatrixValues[Matrix.MSCALE_Y];
      canvas.drawText("Lat: " + lastFix.getLatitude(), tx, ty + 5, mPaint);
      canvas.drawText("Lon: " + lastFix.getLongitude(), tx, ty + 20, mPaint);
      canvas.drawText("Cog: " + lastFix.getBearing(), tx, ty + 35, mPaint);
      canvas.drawText("Acc: " + lastFix.getAccuracy(), tx, ty + 50, mPaint);
      canvas.drawText("Kts: " + lastFix.getSpeed() / 1.94384449, tx, ty + 65, mPaint);
    }

    // TODO: read from compass if available for bearing
    if (lastFix.hasBearing()) {
      /*
       * Rotate the direction-Arrow according to the bearing we are driving. And draw it
       * to the canvas.
       */
      directionRotater.setRotate(
          lastFix.getBearing(), DIRECTION_ARROW_CENTER_X, DIRECTION_ARROW_CENTER_Y);

      directionRotater.postTranslate(-DIRECTION_ARROW_CENTER_X, -DIRECTION_ARROW_CENTER_Y);
      directionRotater.postScale(
          1 / mMatrixValues[Matrix.MSCALE_X], 1 / mMatrixValues[Matrix.MSCALE_Y]);
      directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
      canvas.drawBitmap(DIRECTION_ARROW, directionRotater, mPaint);
    } else {
      directionRotater.setTranslate(-NULLDIRECTION_ICON_CENTER_X, -NULLDIRECTION_ICON_CENTER_Y);
      directionRotater.postScale(
          1 / mMatrixValues[Matrix.MSCALE_X], 1 / mMatrixValues[Matrix.MSCALE_Y]);
      directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
      canvas.drawBitmap(NULLDIRECTION_ICON, directionRotater, mPaint);
    }
  }
Exemplo n.º 11
0
  /**
   * Get lat long double [ ].
   *
   * @return the double [ ]
   */
  @SuppressWarnings("MissingPermission")
  public double[] getLatLong() {
    boolean hasFineLocationPermission =
        context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED;
    boolean isGPSEnabled;
    boolean isNetworkEnabled;

    double[] gps = new double[2];
    gps[0] = 0;
    gps[1] = 0;
    if (hasFineLocationPermission) {
      LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

      isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
      isNetworkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

      Location net_loc = null;
      Location gps_loc = null;
      Location final_loc;

      if (isGPSEnabled) {
        gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
      }
      if (isNetworkEnabled) {
        net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
      }

      if (gps_loc != null && net_loc != null) {
        if (gps_loc.getAccuracy() >= net_loc.getAccuracy()) {
          final_loc = gps_loc;
        } else {
          final_loc = net_loc;
        }
      } else {
        if (gps_loc != null) {
          final_loc = gps_loc;
        } else if (net_loc != null) {
          final_loc = net_loc;
        } else {
          // GPS and Network both are null so try passive
          final_loc = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }
      }

      if (final_loc != null) {
        gps[0] = final_loc.getLatitude();
        gps[1] = final_loc.getLongitude();
      }

      return gps;
    }
    return gps;
  }
Exemplo n.º 12
0
 private void addLocation(Location location, JSONObject object, String prefix)
     throws JSONException {
   object.put(prefix + "_timestamp", location.getTime());
   object.put(prefix + "_speed", location.getSpeed());
   object.put(prefix + "_course", location.getBearing());
   object.put(prefix + "_verticalAccuracy", location.getAccuracy());
   object.put(prefix + "_horizontalAccuracy", location.getAccuracy());
   object.put(prefix + "_altitude", location.getAltitude());
   object.put(prefix + "_latitude", location.getLatitude());
   object.put(prefix + "_longitude", location.getLongitude());
 }
    protected void updateAccuracy(@NonNull Location location) {
      if (accuracyAnimator != null && accuracyAnimator.isRunning()) {
        // use current accuracy as a starting point
        accuracy = (Float) accuracyAnimator.getAnimatedValue();
        accuracyAnimator.end();
      }

      accuracyAnimator = ValueAnimator.ofFloat(accuracy * 10, location.getAccuracy() * 10);
      accuracyAnimator.setDuration(750);
      accuracyAnimator.start();
      accuracy = location.getAccuracy();
    }
  /**
   * Determines whether one Location reading is better than the current Location fix
   *
   * @param location The new Location that you want to evaluate
   * @param currentBestLocation The current Location fix, to which you want to compare the new one
   */
  protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    Log.d(PluginConstants.LOG_TAG, "Location : check ");
    if (currentBestLocation == null) {
      // A new location is always better than no location
      return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
      Log.d(PluginConstants.LOG_TAG, "Location : isSignificantlyNewer ");
      return true;
      // If the new location is more than two minutes older, it must be
      // worse
    } else if (isSignificantlyOlder) {
      Log.d(PluginConstants.LOG_TAG, "Location : isSignificantlyOlder ");
      return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider =
        isSameProvider(location.getProvider(), currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
      Log.d(PluginConstants.LOG_TAG, "Location : isMoreAccurate ");
      return true;
    } else if (isNewer && !isLessAccurate) {
      Log.d(PluginConstants.LOG_TAG, "Location : isNewer && !isLessAccurate ");
      return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
      Log.d(
          PluginConstants.LOG_TAG,
          "Location : isNewer && !isSignificantlyLessAccurate && isFromSameProvider ");
      return true;
    }
    return false;
  }
Exemplo n.º 15
0
    @Override
    public void onLocationChanged(Location location) {

      Log.d(
          "LocationListener",
          "onLocationChanged, "
              + " lon:"
              + location.getLongitude()
              + " lat:"
              + location.getLatitude());
      mLocation = null;
      if (!isShowMyLocationEnabled()) {
        return;
      }
      mLocation = location;
      accuracy = location.getAccuracy();

      if (mSetCenter || isSnapToLocationEnabled()) {
        mSetCenter = false;

        // mTileMap.map.setCenter(point);
        mTileMap.setMapCenter(getLocation(mLocation));
        mTileMap.mapActivity.invalidateMap();
      }
    }
Exemplo n.º 16
0
 @Override
 public void onLocationChanged(Location location) {
   String longitue = "经度:" + location.getLongitude();
   String latitude = "经度:" + location.getLatitude();
   String accuracy = "精确度:" + location.getAccuracy();
   textView.setText(longitue + "\n" + latitude + "\n" + accuracy + "\n");
 }
  @Override
  protected void drawMyLocation(
      Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when) {
    if (!bugged) {
      try {
        super.drawMyLocation(canvas, mapView, lastFix, myLocation, when);
      } catch (Exception e) {
        // we found a buggy phone, draw the location icons ourselves
        bugged = true;
      }
    }

    if (bugged) {
      if (drawable == null) {

        accuracyPaint = new Paint();
        accuracyPaint.setAntiAlias(true);
        accuracyPaint.setStrokeWidth(2.0f);

        drawable =
            mapView
                .getContext()
                .getResources()
                .getDrawable(R.drawable.ic_maps_indicator_current_position);
        width = drawable.getIntrinsicWidth();
        height = drawable.getIntrinsicHeight();
        center = new Point();
        left = new Point();
      }

      Projection projection = mapView.getProjection();
      double latitude = lastFix.getLatitude();
      double longitude = lastFix.getLongitude();
      float accuracy = lastFix.getAccuracy();

      float[] result = new float[1];

      Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
      float longitudeLineDistance = result[0];

      GeoPoint leftGeo =
          new GeoPoint(
              (int) (latitude * 1e6), (int) ((longitude - accuracy / longitudeLineDistance) * 1e6));
      projection.toPixels(leftGeo, left);
      projection.toPixels(myLocation, center);
      int radius = center.x - left.x;

      accuracyPaint.setColor(0xff6666ff);
      accuracyPaint.setStyle(Style.STROKE);
      canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

      accuracyPaint.setColor(0x186666ff);
      accuracyPaint.setStyle(Style.FILL);
      canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

      drawable.setBounds(
          center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2);
      drawable.draw(canvas);
    }
  }
Exemplo n.º 18
0
  private void findBestLastLocation() {
    long minTime = 0;
    float bestAccuracy = Float.MAX_VALUE;
    Location bestResult = null;
    long bestTime = 0;
    List<String> matchingProviders = locationManager.getAllProviders();
    for (String provider : matchingProviders) {
      Location location = locationManager.getLastKnownLocation(provider);
      if (location != null) {
        float accuracy = location.getAccuracy();
        long time = location.getTime();

        if ((time > minTime && accuracy < bestAccuracy)) {
          bestResult = location;
          bestAccuracy = accuracy;
          bestTime = time;
        } else if (time < minTime && bestAccuracy == Float.MAX_VALUE && time > bestTime) {
          bestResult = location;
          bestTime = time;
        }
      }
    }
    if (bestResult != null) {
      Log.d(LOG_TAG, "found best last location: " + bestResult);
      onLocationChanged(bestResult);
    }
  }
  @Override
  public void onLocationChanged(Location location) {
    Log.d(TAG, "- onLocationChanged" + location.toString());

    if (config.isDebugging()) {
      Toast.makeText(
              FusedLocationService.this,
              "acy:"
                  + location.getAccuracy()
                  + ",v:"
                  + location.getSpeed()
                  + ",df:"
                  + config.getDistanceFilter(),
              Toast.LENGTH_LONG)
          .show();
    }

    // if (lastLocation != null && location.distanceTo(lastLocation) < config.getDistanceFilter()) {
    //     return;
    // }

    if (config.isDebugging()) {
      startTone("beep");
    }

    lastLocation = location;
    handleLocation(location);
  }
Exemplo n.º 20
0
  public boolean onLocationChanged(Location location) {
    if (startFixing == -1) {
      startFixing = location.getTime();
    }

    if (location.hasAccuracy()) {
      float accuracy = location.getAccuracy();
      if (minAccuracy > 0) {
        minAccuracy = accuracy;
      } else if (accuracy > minAccuracy) {
        minAccuracy = accuracy;
        averageAccuracy = accuracy;
      }

      averageAccuracy = (averageAccuracy + accuracy) / 2;

      if (accuracy < mFixAccurancy) {
        mIsFixed = true;
        return mIsFixed;
      }
    }

    if (mKnownSatellites >= mFixSatellites) {
      mIsFixed = true;
    } else if ((location.getTime() - startFixing) > mFixTime) {
      mIsFixed = true;
    }
    return mIsFixed;
  }
Exemplo n.º 21
0
  public void addPointNow(Location loc) {
    int lat = (int) (loc.getLatitude() * 1E6);
    int lgt = (int) (loc.getLongitude() * 1E6);

    float accuracy = loc.getAccuracy();
    double altitude = loc.getAltitude();
    float speed = loc.getSpeed();

    endTime_ = (loc.getTime() / 1000);
    CyclePoint pt = new CyclePoint(lat, lgt, endTime_, accuracy, altitude, speed);

    if (gpspoints.size() > 1) {
      CyclePoint gp = gpspoints.get(gpspoints.size() - 1);

      float segmentDistance = gp.distanceTo(pt);
      if (segmentDistance == 0) return; // we haven't gone anywhere

      distance += segmentDistance;
    } // if ...

    gpspoints.add(pt);

    mDb.open();
    mDb.addCoordToTrip(tripid, pt);
    mDb.setDistance(tripid, distance);
    mDb.close();

    return;
  } // addPointNow
Exemplo n.º 22
0
  /**
   * Creates a waypoint under the current track segment with the current time on which the waypoint
   * is reached
   *
   * @param track track
   * @param segment segment
   * @param latitude latitude
   * @param longitude longitude
   * @param time time
   * @param speed the measured speed
   * @return
   */
  long insertWaypoint(long trackId, long segmentId, Location location) {
    if (trackId < 0 || segmentId < 0) {
      throw new IllegalArgumentException("Track and segments may not the less then 0.");
    }

    SQLiteDatabase sqldb = getWritableDatabase();

    ContentValues args = new ContentValues();
    args.put(WaypointsColumns.SEGMENT, segmentId);
    args.put(WaypointsColumns.TIME, location.getTime());
    args.put(WaypointsColumns.LATITUDE, location.getLatitude());
    args.put(WaypointsColumns.LONGITUDE, location.getLongitude());
    args.put(WaypointsColumns.SPEED, location.getSpeed());
    args.put(WaypointsColumns.ACCURACY, location.getAccuracy());
    args.put(WaypointsColumns.ALTITUDE, location.getAltitude());
    args.put(WaypointsColumns.BEARING, location.getBearing());

    //      Log.d( TAG, "Waypoint time stored in the datebase"+ DateFormat.getInstance().format(new
    // Date( args.getAsLong( Waypoints.TIME ) ) ) );

    long waypointId = sqldb.insert(Waypoints.TABLE, null, args);

    ContentResolver resolver = this.mContext.getContentResolver();
    resolver.notifyChange(
        Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints"),
        null);

    return waypointId;
  }
Exemplo n.º 23
0
  public void onLocationChanged(Location location) {
    Log.i("", "onLocationChanged: " + location);

    if (atStop()
        && lastLocation != null
        && distanceFromLocation(currentStop.location, lastLocation) > MIN_DISTANCE * 2) {
      captureActivity.triggerTransitStopDepature();
    }

    if (currentCapture != null && location.getAccuracy() < MIN_ACCURACY * 2) {

      RoutePoint rp = new RoutePoint();
      rp.location = location;
      rp.time = SystemClock.elapsedRealtime();

      currentCapture.points.add(rp);

      if (lastLocation != null) {

        currentCapture.distance += distanceFromLocation(lastLocation, location);

        if (captureActivity != null) captureActivity.updateDistance();
      }

      lastLocation = location;

      if (captureActivity != null) captureActivity.updateGpsStatus();
    }
  }
 @Override
 public void onLocationChanged(Location location) {
   latitude = location.getLatitude();
   longitude = location.getLongitude();
   accuracy = location.getAccuracy();
   altitude = location.getAltitude();
 }
Exemplo n.º 25
0
    @Override
    public void onLocationChanged(Location location) {
      String longitude = "lon:" + location.getLongitude() + "\n";
      String latitude = "lat:" + location.getLatitude() + "\n";
      String accuracy = "acc:" + location.getAccuracy() + "\n";

      // 把标准的GPS坐标转换成火星坐标
      InputStream ips;
      try {
        ips = getAssets().open("axisoffset.dat");
        ModifyOffset offset = ModifyOffset.getInstance(ips);
        PointDouble pd =
            offset.s2c(new PointDouble(location.getLongitude(), location.getLatitude()));
        longitude = "lon:" + pd.x + "\n";
        latitude = "lat:" + pd.y + "\n";
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
      Editor editor = sp.edit();
      editor.putString("lastlocation", longitude + latitude + accuracy);
      editor.commit();
    }
Exemplo n.º 26
0
    @Override
    public void onLocationChanged(Location loc) {
      // save to application context
      MyAppContext mContext = ((MyAppContext) getApplicationContext());
      mContext.mCurrLocation.setLatitude(loc.getLatitude());
      mContext.mCurrLocation.setLongitude(loc.getLongitude());
      mContext.mCurrLocation.setAltitude(loc.getAccuracy());

      // save to persistance storage
      SharedPreferences settings =
          getSharedPreferences(Main.PREFS_NAME, Context.MODE_WORLD_WRITEABLE);
      Editor ed = settings.edit();
      ed.putString("MyLat", String.valueOf(loc.getLatitude()));
      ed.putString("MyLong", String.valueOf(loc.getLongitude()));
      ed.putString("MyAtt", String.valueOf(loc.getAltitude()));
      ed.commit();

      drawText();

      String Text =
          "My current location is:"
              + "\nLatitude = "
              + loc.getLatitude()
              + "\nLongitude = "
              + loc.getLongitude();
      Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
      // unregister
      mLocManager.removeUpdates(mLocListener);
    }
Exemplo n.º 27
0
  /**
   * Creates a waypoint under the current track segment with the current time on which the waypoint
   * is reached
   *
   * @param track track
   * @param segment segment
   * @param latitude latitude
   * @param longitude longitude
   * @param time time
   * @param speed the measured speed
   * @return
   */
  long insertWaypoint(long trackId, long segmentId, Location location) {
    // Log.d( TAG, "New waypoint ("+latitude+","+longitude+") with speed "+speed );
    if (trackId < 0 || segmentId < 0) {
      throw new IllegalArgumentException("Track and segments may not the less then 0.");
    }

    SQLiteDatabase sqldb = getWritableDatabase();

    ContentValues args = new ContentValues();
    args.put(WaypointsColumns.SEGMENT, segmentId);
    args.put(WaypointsColumns.TIME, location.getTime());
    args.put(WaypointsColumns.LATITUDE, location.getLatitude());
    args.put(WaypointsColumns.LONGITUDE, location.getLongitude());
    args.put(WaypointsColumns.SPEED, location.getSpeed());
    args.put(WaypointsColumns.ACCURACY, location.getAccuracy());
    args.put(WaypointsColumns.ALTITUDE, location.getAltitude());
    args.put(WaypointsColumns.BEARING, location.getBearing());

    long waypointId = sqldb.insert(Waypoints.TABLE, null, args);

    ContentResolver resolver = this.mContext.getContentResolver();
    Uri notifyUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId);
    resolver.notifyChange(notifyUri, null);
    notifyUri = Uri.withAppendedPath(notifyUri, "segments/" + segmentId);
    resolver.notifyChange(notifyUri, null);
    notifyUri = Uri.withAppendedPath(notifyUri, "waypoints/" + waypointId);
    resolver.notifyChange(notifyUri, null);

    return waypointId;
  }
Exemplo n.º 28
0
  public Location getValidLastKnownLocation(long maxTime, float minAccuracy) {
    Location bestLocation = null;
    long bestTime = maxTime;
    float bestAccuracy = minAccuracy;
    long now = System.currentTimeMillis();

    List<String> providers = lm.getAllProviders();
    for (String provider : providers) {
      if (!provider.equals(LocationManager.GPS_PROVIDER)) {
        // GPS not used because a bug with location time info
        Location location = lm.getLastKnownLocation(provider);
        if (location != null) {
          float accuracy = location.getAccuracy();
          long time = now - location.getTime();

          if ((time > 0 && time <= bestTime && accuracy <= bestAccuracy)) {
            // time > 0 to elude a problem with some GPS time information
            bestLocation = location;
            bestAccuracy = accuracy;
            bestTime = time;
          }
        }
      }
    }
    return bestLocation;
  }
Exemplo n.º 29
0
  @Override
  public void onLocationChanged(Location location) {
    if (location.hasAccuracy()) {
      SpannableString s = new SpannableString(String.format("%.0f", location.getAccuracy()) + "m");
      s.setSpan(new RelativeSizeSpan(0.75f), s.length() - 1, s.length(), 0);
      accuracy.setText(s);

      if (firstfix) {
        status.setText("");
        fab.setVisibility(View.VISIBLE);
        if (!data.isRunning() && !maxSpeed.getText().equals("")) {
          refresh.setVisibility(View.VISIBLE);
        }
        firstfix = false;
      }
    } else {
      firstfix = true;
    }

    if (location.hasSpeed()) {
      progressBarCircularIndeterminate.setVisibility(View.GONE);
      SpannableString s =
          new SpannableString(String.format("%.0f", location.getSpeed() * 3.6) + "km/h");
      s.setSpan(new RelativeSizeSpan(0.25f), s.length() - 4, s.length(), 0);
      currentSpeed.setText(s);
    }
  }
Exemplo n.º 30
0
 private void test05GetLastLocation() {
   mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
   Log.i(TAG, "test05GetLastLocation call getLastLocation()");
   Location location = mLocationManager.getLastLocation();
   Bundle bundle = new Bundle();
   if (location != null) {
     Log.i(TAG, "getLastLocation() return not null");
     bundle.putString(
         KEY_LOC,
         "getLatitude: "
             + location.getLatitude()
             + " getLongitude: "
             + location.getLongitude()
             + " getAltitude: "
             + location.getAltitude()
             + " getAccuracy: "
             + location.getAccuracy()
             + " getBearing: "
             + location.getBearing()
             + " getSpeed: "
             + location.getSpeed());
   } else {
     Log.i(TAG, "getLastLocation() return null");
   }
   removeDialog(DIALOG_LOC);
   showDialog(DIALOG_LOC, bundle);
 }