Ejemplo n.º 1
2
  /**
   * 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;
  }
  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);
    }
  }
Ejemplo n.º 3
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);
 }
  public void onLocationChanged(final Location location) {
    if (DEBUGMODE) {
      logger.debug("onLocationChanged(" + location + ")");
    }
    // ignore temporary non-gps fix
    if (mIgnorer.shouldIgnore(location.getProvider(), System.currentTimeMillis())) {
      logger.debug("Ignore temporary non-gps location");
      return;
    }

    mLocation = location;
    if (mFollow) {
      mMapController.setCenter(new GeoPoint(location));
    } else {
      mMapView.postInvalidate(); // redraw the my location icon
    }

    for (final Runnable runnable : mRunOnFirstFix) {
      new Thread(runnable).start();
    }
    mRunOnFirstFix.clear();

    sogTxt.setText(
        String.valueOf((double) Math.round(location.getSpeed() * 1.94 * 100) / 100) + "kts | ");
    cogTxt.setText(String.valueOf(location.getBearing()) + "\u00B0 ");
  }
  /**
   * 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;
  }
  /**
   * 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;
  }
Ejemplo n.º 7
0
    public void onLocationChanged(Location loc) {
      System.out.println("GPS scan received");
      String record =
          gpsStatusCode
              + PayloadFieldDelimiter
              + loc.getTime()
              + PayloadFieldDelimiter
              + loc.getLatitude()
              + PayloadFieldDelimiter
              + loc.getLongitude()
              + PayloadFieldDelimiter
              + loc.getAltitude()
              + PayloadFieldDelimiter
              + loc.getAccuracy()
              + PayloadFieldDelimiter
              + loc.getSpeed()
              + PayloadFieldDelimiter
              + loc.getBearing()
              + PayloadFieldDelimiter
              + curGroundTruth;
      ;

      String timestamp = System.currentTimeMillis() + "";
      logger.writeRecord(type, timestamp, record);
      debugStatus = LifeLogService.getReadableCurrentTime();
    }
Ejemplo n.º 8
0
  public void locationUpdated(LocationManager manager, Location location, boolean lastKnown) {
    // #debug info
    logger.info("updateLocation: " + location);
    if (location == null) {
      return;
    }
    hasFix = true;
    if (currentState != LocationProvider.AVAILABLE) {
      updateSolution(LocationProvider.AVAILABLE);
    }
    lastFixTimestamp = System.currentTimeMillis();
    // #debug debug
    logger.debug("received Location: " + location);

    pos.latitude = (float) location.getLatitude();
    pos.longitude = (float) location.getLongitude();
    pos.altitude = (float) location.getAltitude();
    pos.course = location.getBearing();
    pos.speed = location.getSpeed();
    pos.timeMillis = location.getTime();
    pos.accuracy = location.getAccuracy();
    if (lastKnown) {
      pos.type = Position.TYPE_GPS_LASTKNOWN;
    } else {
      pos.type = Position.TYPE_GPS;
    }
    receiverList.receivePosition(pos);
    // logger.trace("exit locationUpdated(provider,location)");
  }
Ejemplo n.º 9
0
 private void updateDials(
     Waypoint actual, Waypoint desired, ErrorVector error, Location location) {
   System.out.println("Updating Dials");
   compassView.setBearing(location.getBearing());
   compassView.setGlide(error.magVert);
   compassView.setCourseBearing(ErrorVector.courseBearing(desired));
   compassView.setCourseDeviation(error.XTE);
   compassView.setATE(error.ATE);
   compassView.setDistance(error.magHorz);
   compassView.setDesiredVelocity(ErrorVector.velocityRequired(actual, desired)[0]);
   compassView.setDVelocityAngle(ErrorVector.velocityRequired(actual, desired)[1]);
   compassView.setVelocityExcess(location.getSpeed());
   compassView.setVelocityExcessAngle(location.getBearing());
   compassView.setTime(actual.time);
   compassView.setCurrent((int) desired.time);
   compassView.invalidate();
 }
 public Position(String deviceId, Location location, double battery) {
   this.deviceId = deviceId;
   time = new Date(location.getTime());
   latitude = location.getLatitude();
   longitude = location.getLongitude();
   altitude = location.getAltitude();
   speed = location.getSpeed() * 1.943844; // speed in knots
   course = location.getBearing();
   this.battery = battery;
 }
 public static GenericData createGenericData(Location location) {
   GPS gps =
       new GPS(
           location.getLatitude(),
           location.getLongitude(),
           location.getSpeed(),
           location.getBearing(),
           location.getAltitude(),
           location.getTime());
   return gps;
 }
    @Override
    void updateLatLng(@NonNull Location location) {
      if (latLng == null) {
        // first location fix
        latLng = new LatLng(location);
        locationUpdateTimestamp = SystemClock.elapsedRealtime();
      }

      // updateLatLng timestamp
      long previousUpdateTimeStamp = locationUpdateTimestamp;
      locationUpdateTimestamp = SystemClock.elapsedRealtime();

      // calculate animation duration
      long locationUpdateDuration;
      if (previousUpdateTimeStamp == 0) {
        locationUpdateDuration = 0;
      } else {
        // TODO remove 10 * hack to multiply duration to workaround easing interpolation
        // (easeCamera)
        locationUpdateDuration = 10 * (locationUpdateTimestamp - previousUpdateTimeStamp);
      }

      // calculate interpolated location
      previousLocation = latLng;
      latLng = new LatLng(location);
      interpolatedLocation =
          new LatLng(
              (latLng.getLatitude() + previousLocation.getLatitude()) / 2,
              (latLng.getLongitude() + previousLocation.getLongitude()) / 2);

      // build new camera
      CameraPosition.Builder builder = new CameraPosition.Builder().target(interpolatedLocation);

      // add direction
      if (myBearingTrackingMode == MyBearingTracking.GPS) {
        if (location.hasBearing()) {
          builder.bearing(location.getBearing());
          gpsDirection = 0;
        }
      } else if (myBearingTrackingMode == MyBearingTracking.COMPASS) {
        if (!compassListener.isPaused()) {
          builder.bearing(compassListener.getCurrentDegree());
          compassDirection = 0;
        }
      }

      updateAccuracy(location);

      // animate to new camera
      mapboxMap.easeCamera(
          CameraUpdateFactory.newCameraPosition(builder.build()),
          (int) locationUpdateDuration,
          null);
    }
Ejemplo n.º 13
0
  ContentValues createContentValues(Waypoint waypoint) {
    ContentValues values = new ContentValues();

    // Value < 0 indicates no id is available
    if (waypoint.getId() >= 0) {
      values.put(WaypointsColumns._ID, waypoint.getId());
    }
    values.put(WaypointsColumns.NAME, waypoint.getName());
    values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription());
    values.put(WaypointsColumns.CATEGORY, waypoint.getCategory());
    values.put(WaypointsColumns.ICON, waypoint.getIcon());
    values.put(WaypointsColumns.TRACKID, waypoint.getTrackId());
    values.put(WaypointsColumns.TYPE, waypoint.getType());
    values.put(WaypointsColumns.LENGTH, waypoint.getLength());
    values.put(WaypointsColumns.DURATION, waypoint.getDuration());
    values.put(WaypointsColumns.STARTID, waypoint.getStartId());
    values.put(WaypointsColumns.STOPID, waypoint.getStopId());

    Location location = waypoint.getLocation();
    if (location != null) {
      values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6));
      values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6));
      values.put(WaypointsColumns.TIME, location.getTime());
      if (location.hasAltitude()) {
        values.put(WaypointsColumns.ALTITUDE, location.getAltitude());
      }
      if (location.hasAccuracy()) {
        values.put(WaypointsColumns.ACCURACY, location.getAccuracy());
      }
      if (location.hasSpeed()) {
        values.put(WaypointsColumns.SPEED, location.getSpeed());
      }
      if (location.hasBearing()) {
        values.put(WaypointsColumns.BEARING, location.getBearing());
      }
    }

    TripStatistics tripStatistics = waypoint.getTripStatistics();
    if (tripStatistics != null) {
      values.put(WaypointsColumns.STARTTIME, tripStatistics.getStartTime());
      values.put(WaypointsColumns.TOTALDISTANCE, tripStatistics.getTotalDistance());
      values.put(WaypointsColumns.TOTALTIME, tripStatistics.getTotalTime());
      values.put(WaypointsColumns.MOVINGTIME, tripStatistics.getMovingTime());
      values.put(WaypointsColumns.AVGSPEED, tripStatistics.getAverageSpeed());
      values.put(WaypointsColumns.AVGMOVINGSPEED, tripStatistics.getAverageMovingSpeed());
      values.put(WaypointsColumns.MAXSPEED, tripStatistics.getMaxSpeed());
      values.put(WaypointsColumns.MINELEVATION, tripStatistics.getMinElevation());
      values.put(WaypointsColumns.MAXELEVATION, tripStatistics.getMaxElevation());
      values.put(WaypointsColumns.ELEVATIONGAIN, tripStatistics.getTotalElevationGain());
      values.put(WaypointsColumns.MINGRADE, tripStatistics.getMinGrade());
      values.put(WaypointsColumns.MAXGRADE, tripStatistics.getMaxGrade());
    }
    return values;
  }
Ejemplo n.º 14
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());
 }
Ejemplo n.º 15
0
  /** Format location message */
  public static String createLocationMessage(boolean extended, Location l, double battery) {
    StringBuilder s = new StringBuilder(extended ? "$TRCCR," : "$GPRMC,");
    Formatter f = new Formatter(s, Locale.ENGLISH);
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
    calendar.setTimeInMillis(l.getTime());

    if (extended) {

      f.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS.%1$tL,A,", calendar);

      f.format("%.6f,%.6f,", l.getLatitude(), l.getLongitude());
      f.format("%.2f,%.2f,", l.getSpeed() * 1.943844, l.getBearing());
      f.format("%.2f,", l.getAltitude());
      f.format("%.0f,", battery);

    } else {

      f.format("%1$tH%1$tM%1$tS.%1$tL,A,", calendar);

      double lat = l.getLatitude();
      double lon = l.getLongitude();
      f.format("%02d%07.4f,%c,", (int) Math.abs(lat), Math.abs(lat) % 1 * 60, lat < 0 ? 'S' : 'N');
      f.format("%03d%07.4f,%c,", (int) Math.abs(lon), Math.abs(lon) % 1 * 60, lon < 0 ? 'W' : 'E');

      double speed = l.getSpeed() * 1.943844; // speed in knots
      f.format("%.2f,%.2f,", speed, l.getBearing());
      f.format("%1$td%1$tm%1$ty,,", calendar);
    }

    byte checksum = 0;
    for (byte b : s.substring(1).getBytes()) {
      checksum ^= b;
    }
    f.format("*%02x\r\n", (int) checksum);
    f.close();

    return s.toString();
  }
Ejemplo n.º 16
0
 private void updateNewLocation(Location location) {
   LocationProviderAdapter.newLocationAvailable(
       location.getLatitude(),
       location.getLongitude(),
       location.getTime() / 1000.0,
       location.hasAltitude(),
       location.getAltitude(),
       location.hasAccuracy(),
       location.getAccuracy(),
       location.hasBearing(),
       location.getBearing(),
       location.hasSpeed(),
       location.getSpeed());
 }
    @Override
    void updateLatLng(@NonNull final Location location) {
      if (latLng == null) {
        // first location update
        latLng = new LatLng(location);
        locationUpdateTimestamp = SystemClock.elapsedRealtime();
      }

      // update LatLng location
      previousLocation = latLng;
      latLng = new LatLng(location);

      // update LatLng direction
      if (location.hasBearing()) {
        gpsDirection = clamp(location.getBearing() - (float) mapboxMap.getCameraPosition().bearing);
      }

      // update LatLng accuracy
      updateAccuracy(location);

      // calculate updateLatLng time + add some extra offset to improve animation
      long previousUpdateTimeStamp = locationUpdateTimestamp;
      locationUpdateTimestamp = SystemClock.elapsedRealtime();
      long locationUpdateDuration =
          (long) ((locationUpdateTimestamp - previousUpdateTimeStamp) * 1.2);

      // calculate interpolated entity
      interpolatedLocation =
          new LatLng(
              (latLng.getLatitude() + previousLocation.getLatitude()) / 2,
              (latLng.getLongitude() + previousLocation.getLongitude()) / 2);

      // animate changes
      if (locationChangeAnimator != null) {
        locationChangeAnimator.end();
        locationChangeAnimator = null;
      }

      locationChangeAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
      locationChangeAnimator.setDuration((long) (locationUpdateDuration * 1.2));
      locationChangeAnimator.addUpdateListener(
          new MarkerCoordinateAnimatorListener(this, previousLocation, interpolatedLocation));
      locationChangeAnimator.setInterpolator(new FastOutLinearInInterpolator());
      locationChangeAnimator.start();

      // use interpolated location as current location
      latLng = interpolatedLocation;
    }
Ejemplo n.º 18
0
 public void onLocationChanged(Location location) {
   showToast(
       "onLocationChanged() return: "
           + " getLatitude: "
           + location.getLatitude()
           + " getLongitude: "
           + location.getLongitude()
           + " getAltitude: "
           + location.getAltitude()
           + " getAccuracy: "
           + location.getAccuracy()
           + " getBearing: "
           + location.getBearing()
           + " getSpeed: "
           + location.getSpeed());
 }
Ejemplo n.º 19
0
  @Override
  public void onLocationChanged(Location location) {
    String text =
        String.format(
            Locale.getDefault(),
            "\nLat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f",
            location.getLatitude(),
            location.getLongitude(),
            location.getAltitude(),
            location.getBearing());
    Log.d(TAG, "onLocationChanged with location " + text);

    for (LocationChangedListener changedListener : listeners) {
      changedListener.onLocationChanged(location);
    }
  }
  @Implementation
  public void set(Location l) {
    time = l.getTime();
    provider = l.getProvider();
    latitude = l.getLatitude();
    longitude = l.getLongitude();
    accuracy = l.getAccuracy();
    bearing = l.getBearing();
    altitude = l.getAltitude();
    speed = l.getSpeed();

    hasAccuracy = l.hasAccuracy();
    hasAltitude = l.hasAltitude();
    hasBearing = l.hasBearing();
    hasSpeed = l.hasSpeed();
  }
Ejemplo n.º 21
0
  public static de.uvwxy.daisy.proto.Messages.Location androidLocationToProtoLocation(
      android.location.Location androLoc) {
    Preconditions.checkNotNull(androLoc);

    Messages.Location.Builder locBuilder = Messages.Location.newBuilder();
    locBuilder.setLatitude(androLoc.getLatitude());
    locBuilder.setLongitude(androLoc.getLongitude());
    locBuilder.setAltitude(androLoc.getAltitude());
    locBuilder.setBearing(androLoc.getBearing());
    locBuilder.setAccuracy(androLoc.getAccuracy());
    locBuilder.setTime(androLoc.getTime());
    locBuilder.setSpeed(androLoc.getSpeed());
    locBuilder.setProvider(androLoc.getProvider());

    return locBuilder.build();
  }
Ejemplo n.º 22
0
 public void createRouteTo(Location location) {
   mapController.clearLines();
   mapFragment.clearMarkers();
   mapFragment.updateMap();
   isRouting = true;
   act.showLoadingIndicator();
   router
       .clearLocations()
       .setLocation(locationToPair(location))
       // To allow routing to see which direction you are travelling
       .setLocation(
           locationToPair(
               getDistancePointFromBearing(location, 15, (int) Math.floor(location.getBearing()))))
       .setLocation(geoPointToPair(SimpleFeatureHelper.getGeoPoint(simpleFeature)))
       .setCallback(this)
       .fetch();
 }
Ejemplo n.º 23
0
 private void getLocation(StringBuilder sb, Location loc) {
   if (loc == null) {
     Log.d(TAG, "loc is null");
     return;
   }
   sb.append(
       String.format(
           "Lat:%f\nLong:%f\nAlt:%f\nBearing:%f\n",
           loc.getLatitude(), loc.getLongitude(), loc.getAltitude(), loc.getBearing()));
   // Perform geocidng for this location
   try {
     List<Address> addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 10);
     for (Address addr : addresses) {
       sb.append(addr.getAddressLine(0) + "\n");
     }
   } catch (IOException e) {
   }
 }
Ejemplo n.º 24
0
 ///////// Location provider callbacks
 public void onLocationChanged(Location loc) {
   DataOutputStream file = fout[1];
   if (file == null)
     // Something is wrong
     return;
   long tim = System.currentTimeMillis();
   int typ = loc.getProvider().length(); // Seems a good identifier
   try {
     file.writeInt(typ);
     file.writeLong(tim);
     file.writeLong(loc.getTime());
     file.writeFloat(loc.getAccuracy());
     file.writeDouble(loc.getAltitude());
     file.writeDouble(loc.getLatitude());
     file.writeDouble(loc.getLongitude());
     file.writeFloat(loc.getBearing());
     file.writeFloat(loc.getSpeed());
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 25
0
  @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
  public static JSONObject location2Json(Location location) throws JSONException {
    JSONObject latLng = new JSONObject();
    latLng.put("lat", location.getLatitude());
    latLng.put("lng", location.getLongitude());

    JSONObject params = new JSONObject();
    params.put("latLng", latLng);

    if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      params.put("elapsedRealtimeNanos", location.getElapsedRealtimeNanos());
    } else {
      params.put("elapsedRealtimeNanos", 0);
    }
    params.put("time", location.getTime());
    /*
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date date = new Date(location.getTime());
    params.put("timeFormatted", format.format(date));
    */
    if (location.hasAccuracy()) {
      params.put("accuracy", location.getAccuracy());
    }
    if (location.hasBearing()) {
      params.put("bearing", location.getBearing());
    }
    if (location.hasAltitude()) {
      params.put("altitude", location.getAltitude());
    }
    if (location.hasSpeed()) {
      params.put("speed", location.getSpeed());
    }
    params.put("provider", location.getProvider());
    params.put("hashCode", location.hashCode());
    return params;
  }
Ejemplo n.º 26
0
  void success(Location loc) {
    /*
     * We only need to figure out what we do when we succeed!
     */

    String params;
    /*
     * Build the giant string to send back to Javascript!
     */
    params =
        loc.getLatitude()
            + ","
            + loc.getLongitude()
            + ", "
            + loc.getAltitude()
            + ","
            + loc.getAccuracy()
            + ","
            + loc.getBearing();
    params += "," + loc.getSpeed() + "," + loc.getTime();
    if (id != "global") {
      mAppView.loadUrl("javascript:navigator.geolocation.success(" + id + "," + params + ")");
    }
  }
Ejemplo n.º 27
0
  public void updateMap(Location location) {
    Log.i(TAG, " Holy Moley ..." + location.toString());
    UserObject o =
        new UserObject("user", "" + location.getLatitude(), "" + location.getLongitude());

    userInfo.enqueue(o);
    userInfo.enqueueLoc(location);
    Log.i(TAG, "new co-ordinates: ========> " + o.getLast_lat() + o.getLast_long());
    userSession.setCurrLat(location.getLatitude());
    userSession.setCurrLng(location.getLongitude());

    // To avoid the case where we don't have enough data points
    if (userInfo.size() > 1) {
      UserObject lastInfo = userInfo.dequeue();
      Location dest = userInfo.dequeueLoc();

      //            calcSpeed(location.getLatitude(), location.getLongitude(),
      //                        lastInfo.getLast_lat_double(), lastInfo.getLast_long_double());
      calcSpeed(location, dest);
    }

    // Update friends locations
    if (!userSession.friends.isEmpty()) {
      Enumeration e = userSession.friends.elements();
      while (e.hasMoreElements()) {
        Log.i(TAG, " next friend ");
        updateFriendMarker((UserObject) e.nextElement());
      }
    }

    if (location.hasBearing()) {
      gotoMyLocation(location.getLatitude(), location.getLongitude(), location.getBearing());
    } else {
      gotoMyLocation(location.getLatitude(), location.getLongitude(), 0f);
    }
  }
Ejemplo n.º 28
0
  /**
   * Given a location fix, processes it and displays it in the table on the form.
   *
   * @param loc Location information
   */
  private void DisplayLocationInfo(Location loc) {
    Utilities.LogDebug("GpsMainActivity.DisplayLocationInfo");
    try {

      if (loc == null) {
        return;
      }

      TextView tvLatitude = (TextView) findViewById(R.id.txtLatitude);
      TextView tvLongitude = (TextView) findViewById(R.id.txtLongitude);
      TextView tvDateTime = (TextView) findViewById(R.id.txtDateTimeAndProvider);

      TextView tvAltitude = (TextView) findViewById(R.id.txtAltitude);

      TextView txtSpeed = (TextView) findViewById(R.id.txtSpeed);

      TextView txtSatellites = (TextView) findViewById(R.id.txtSatellites);
      TextView txtDirection = (TextView) findViewById(R.id.txtDirection);
      TextView txtAccuracy = (TextView) findViewById(R.id.txtAccuracy);
      String providerName = loc.getProvider();

      if (providerName.equalsIgnoreCase("gps")) {
        providerName = getString(R.string.providername_gps);
      } else {
        providerName = getString(R.string.providername_celltower);
      }

      tvDateTime.setText(
          new Date(Session.getLatestTimeStamp()).toLocaleString()
              + getString(R.string.providername_using, providerName));
      tvLatitude.setText(String.valueOf(loc.getLatitude()));
      tvLongitude.setText(String.valueOf(loc.getLongitude()));

      if (loc.hasAltitude()) {

        double altitude = loc.getAltitude();

        if (AppSettings.shouldUseImperial()) {
          tvAltitude.setText(
              String.valueOf(Utilities.MetersToFeet(altitude)) + getString(R.string.feet));
        } else {
          tvAltitude.setText(String.valueOf(altitude) + getString(R.string.meters));
        }

      } else {
        tvAltitude.setText(R.string.not_applicable);
      }

      if (loc.hasSpeed()) {

        float speed = loc.getSpeed();
        String unit;
        if (AppSettings.shouldUseImperial()) {
          if (speed > 1.47) {
            speed = speed * 0.6818f;
            unit = getString(R.string.miles_per_hour);

          } else {
            speed = Utilities.MetersToFeet(speed);
            unit = getString(R.string.feet_per_second);
          }
        } else {
          if (speed > 0.277) {
            speed = speed * 3.6f;
            unit = getString(R.string.kilometers_per_hour);
          } else {
            unit = getString(R.string.meters_per_second);
          }
        }

        txtSpeed.setText(String.valueOf(speed) + unit);

      } else {
        txtSpeed.setText(R.string.not_applicable);
      }

      if (loc.hasBearing()) {

        float bearingDegrees = loc.getBearing();
        String direction;

        direction = Utilities.GetBearingDescription(bearingDegrees, getApplicationContext());

        txtDirection.setText(
            direction
                + "("
                + String.valueOf(Math.round(bearingDegrees))
                + getString(R.string.degree_symbol)
                + ")");
      } else {
        txtDirection.setText(R.string.not_applicable);
      }

      if (!Session.isUsingGps()) {
        txtSatellites.setText(R.string.not_applicable);
        Session.setSatelliteCount(0);
      }

      if (loc.hasAccuracy()) {

        float accuracy = loc.getAccuracy();

        if (AppSettings.shouldUseImperial()) {
          txtAccuracy.setText(
              getString(
                  R.string.accuracy_within,
                  String.valueOf(Utilities.MetersToFeet(accuracy)),
                  getString(R.string.feet)));

        } else {
          txtAccuracy.setText(
              getString(
                  R.string.accuracy_within, String.valueOf(accuracy), getString(R.string.meters)));
        }

      } else {
        txtAccuracy.setText(R.string.not_applicable);
      }

    } catch (Exception ex) {
      SetStatus(getString(R.string.error_displaying, ex.getMessage()));
    }
  }
Ejemplo n.º 29
0
 public double getBearing() {
   if (location != null) {
     bearing = location.getBearing();
   }
   return bearing;
 }
Ejemplo n.º 30
0
  public Location getLocation() {
    try {
      locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

      // getting GPS status
      isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

      // getting network status
      isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

      if (!isGPSEnabled && !isNetworkEnabled) {
        // no network provider is enabled
      } else {
        this.canGetLocation = true;
        // First get location from Network Provider
        if (isNetworkEnabled) {
          locationManager.requestLocationUpdates(
              LocationManager.NETWORK_PROVIDER,
              MIN_TIME_BW_UPDATES,
              MIN_DISTANCE_CHANGE_FOR_UPDATES,
              this);
          Log.d("Network", "Network");
          if (locationManager != null) {
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
              latitude = location.getLatitude();
              longitude = location.getLongitude();
              altitude = location.getAltitude();
              speed = location.getSpeed();
              bearing = location.getBearing();
            }
          }
        }
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled) {
          if (location == null) {
            locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                MIN_TIME_BW_UPDATES,
                MIN_DISTANCE_CHANGE_FOR_UPDATES,
                this);
            Log.d("GPS Enabled", "GPS Enabled");
            if (locationManager != null) {
              location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
              if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                altitude = location.getAltitude();
                speed = location.getSpeed();
                bearing = location.getBearing();
              }
            }
          }
        }
      }

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

    return location;
  }