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

The following examples show how to use android.location.Location#hasBearing() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void injectBestLocation(Location location) {
    int gnssLocationFlags = LOCATION_HAS_LAT_LONG |
            (location.hasAltitude() ? LOCATION_HAS_ALTITUDE : 0) |
            (location.hasSpeed() ? LOCATION_HAS_SPEED : 0) |
            (location.hasBearing() ? LOCATION_HAS_BEARING : 0) |
            (location.hasAccuracy() ? LOCATION_HAS_HORIZONTAL_ACCURACY : 0) |
            (location.hasVerticalAccuracy() ? LOCATION_HAS_VERTICAL_ACCURACY : 0) |
            (location.hasSpeedAccuracy() ? LOCATION_HAS_SPEED_ACCURACY : 0) |
            (location.hasBearingAccuracy() ? LOCATION_HAS_BEARING_ACCURACY : 0);

    double latitudeDegrees = location.getLatitude();
    double longitudeDegrees = location.getLongitude();
    double altitudeMeters = location.getAltitude();
    float speedMetersPerSec = location.getSpeed();
    float bearingDegrees = location.getBearing();
    float horizontalAccuracyMeters = location.getAccuracy();
    float verticalAccuracyMeters = location.getVerticalAccuracyMeters();
    float speedAccuracyMetersPerSecond = location.getSpeedAccuracyMetersPerSecond();
    float bearingAccuracyDegrees = location.getBearingAccuracyDegrees();
    long timestamp = location.getTime();
    native_inject_best_location(gnssLocationFlags, latitudeDegrees, longitudeDegrees,
            altitudeMeters, speedMetersPerSec, bearingDegrees, horizontalAccuracyMeters,
            verticalAccuracyMeters, speedAccuracyMetersPerSecond, bearingAccuracyDegrees,
            timestamp);
}
 
Example 2
Source File: RouteFetcher.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
@Nullable
private NavigationRoute.Builder buildRequestFromLocation(Location location, RouteProgress progress) {
  Context context = contextWeakReference.get();
  if (context == null) {
    return null;
  }
  Point origin = Point.fromLngLat(location.getLongitude(), location.getLatitude());
  Double bearing = location.hasBearing() ? Float.valueOf(location.getBearing()).doubleValue() : null;
  RouteOptions options = progress.directionsRoute().routeOptions();
  NavigationRoute.Builder builder = NavigationRoute.builder(context)
    .origin(origin, bearing, BEARING_TOLERANCE)
    .routeOptions(options);

  List<Point> remainingWaypoints = routeUtils.calculateRemainingWaypoints(progress);
  if (remainingWaypoints == null) {
    Timber.e("An error occurred fetching a new route");
    return null;
  }
  addDestination(remainingWaypoints, builder);
  addWaypoints(remainingWaypoints, builder);
  addWaypointNames(progress, builder);
  addApproaches(progress, builder);
  return builder;
}
 
Example 3
Source File: BackgroundLocation.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
public static BackgroundLocation fromLocation(Location location) {
    BackgroundLocation l = new BackgroundLocation();

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

    return l;
}
 
Example 4
Source File: BackgroundService.java    From BackPackTrackII 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 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: 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 7
Source File: GearService.java    From WheelLogAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onLocationChanged(Location location) {
        if(bHasSpeed = location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasAltitude = location.hasAltitude())
            mAltitude = location.getAltitude();
        if(location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasBearing = location.hasBearing())
            mBearing = location.getBearing();
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        mTime = location.getTime();
//        transmitMessage(); Me lo he llevado a la rutina que se ejecuta de forma temporizada
    }
 
Example 8
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 9
Source File: MainPresenter.java    From open-location-code with Apache License 2.0 5 votes vote down vote up
public void currentLocationUpdated(Location location) {
    if (location.hasBearing() && getCurrentOpenLocationCode() != null) {
        Direction direction =
                DirectionUtil.getDirection(location, getCurrentOpenLocationCode());
        mDirectionActionsListener.directionUpdated(direction);
    }
    if (mCurrentLocation == null) {
        // This is the first location received, so we can move the map to this position.
        mMapActionsListener.setMapCameraPosition(
                location.getLatitude(), location.getLongitude(), MyMapView.INITIAL_MAP_ZOOM);
    }
    mCurrentLocation = location;
}
 
Example 10
Source File: UserLocationOverlay.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public PointF getDrawingPositionOnScreen(final Projection projection, Location lastFix,
        PointF reuse) {
    reuse = getPositionOnScreen(projection, reuse);
    if (lastFix.hasBearing()) {
        reuse.offset(mPersonHotspot.x * mPersonBitmap.getWidth(),
                mPersonHotspot.y * mPersonBitmap.getWidth());
    } else {
        reuse.offset(mDirectionHotspot.x * mDirectionArrowBitmap.getWidth(),
                mDirectionHotspot.y * mDirectionArrowBitmap.getWidth());
    }
    return reuse;
}
 
Example 11
Source File: MyTracksProviderUtilsImpl.java    From mytracks with Apache License 2.0 4 votes vote down vote up
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().ordinal());
  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());
    values.put(WaypointsColumns.CALORIE, tripStatistics.getCalorie());
  }
  
  values.put(WaypointsColumns.PHOTOURL, waypoint.getPhotoUrl());    
  return values;
}
 
Example 12
Source File: CsvTrackWriter.java    From mytracks with Apache License 2.0 4 votes vote down vote up
private String getBearing(Location location) {
  return location.hasBearing() ? Double.toString(location.getBearing()) : null;
}
 
Example 13
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 14
Source File: UserLocationOverlay.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void drawMyLocation(final ISafeCanvas canvas, final MapView mapView, final Location lastFix) {

        final Rect mapBounds = new Rect(0, 0, mapView.getMeasuredWidth(), mapView.getMeasuredHeight());
        final Projection projection = mapView.getProjection();
        Rect rect = new Rect();
        getDrawingBounds(projection, lastFix, null).round(rect);
        if (!Rect.intersects(mapBounds, rect)) {
            //dont draw item if offscreen
            return;
        }
        projection.toMapPixels(mLatLng, mMapCoords);
        final float mapScale = 1 / mapView.getScale();

        canvas.save();

        canvas.scale(mapScale, mapScale, mMapCoords.x, mMapCoords.y);

        if (mDrawAccuracyEnabled) {
            final float radius = lastFix.getAccuracy() / (float) Projection.groundResolution(
                    lastFix.getLatitude(), mapView.getZoomLevel()) * mapView.getScale();
            canvas.save();
            // Rotate the icon
            canvas.rotate(lastFix.getBearing(), mMapCoords.x, mMapCoords.y);
            // Counteract any scaling that may be happening so the icon stays the same size

            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.restore();
        }

        if (UtilConstants.DEBUGMODE) {
            final float tx = (mMapCoords.x + 50);
            final float ty = (mMapCoords.y - 20);
            canvas.drawText("Lat: " + lastFix.getLatitude(), tx, ty + 5, mPaint);
            canvas.drawText("Lon: " + lastFix.getLongitude(), tx, ty + 20, mPaint);
            canvas.drawText("Alt: " + lastFix.getAltitude(), tx, ty + 35, mPaint);
            canvas.drawText("Acc: " + lastFix.getAccuracy(), tx, ty + 50, mPaint);
        }

        if (lastFix.hasBearing()) {
            canvas.save();
            // Rotate the icon
            canvas.rotate(lastFix.getBearing(), mMapCoords.x, mMapCoords.y);
            // Draw the bitmap
            canvas.translate(-mDirectionArrowBitmap.getWidth() * mDirectionHotspot.x,
                    -mDirectionArrowBitmap.getHeight() * mDirectionHotspot.y);

            canvas.drawBitmap(mDirectionArrowBitmap, mMapCoords.x, mMapCoords.y, mPaint);
            canvas.restore();
        } else {
            canvas.save();
            // Unrotate the icon if the maps are rotated so the little man stays upright
            canvas.rotate(-mMapView.getMapOrientation(), mMapCoords.x, mMapCoords.y);
            // Counteract any scaling that may be happening so the icon stays the same size
            canvas.translate(-mPersonBitmap.getWidth() * mPersonHotspot.x,
                    -mPersonBitmap.getHeight() * mPersonHotspot.y);
            // Draw the bitmap
            canvas.drawBitmap(mPersonBitmap, mMapCoords.x, mMapCoords.y, mPaint);
            canvas.restore();
        }
        canvas.restore();
    }
 
Example 15
Source File: MyLocationNewOverlay.java    From osmdroid with Apache License 2.0 4 votes vote down vote up
protected void drawMyLocation(final Canvas canvas, final Projection pj, final Location lastFix) {
	pj.toPixels(mGeoPoint, mDrawPixel);

	if (mDrawAccuracyEnabled) {
		final float radius = lastFix.getAccuracy()
				/ (float) TileSystem.GroundResolution(lastFix.getLatitude(),
						pj.getZoomLevel());

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

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

	if (lastFix.hasBearing()) {
		canvas.save();
		// Rotate the icon if we have a GPS fix, take into account if the map is already rotated
		float mapRotation;
		mapRotation=lastFix.getBearing();
		if (mapRotation >=360.0f)
			mapRotation=mapRotation-360f;
		canvas.rotate(mapRotation, mDrawPixel.x, mDrawPixel.y);
		// Draw the bitmap
		canvas.drawBitmap(mDirectionArrowBitmap, mDrawPixel.x
				- mDirectionArrowCenterX, mDrawPixel.y - mDirectionArrowCenterY,
				mPaint);
		canvas.restore();
	} else {
		canvas.save();
		// Unrotate the icon if the maps are rotated so the little man stays upright
		canvas.rotate(-mMapView.getMapOrientation(), mDrawPixel.x,
				mDrawPixel.y);
		// Draw the bitmap
		canvas.drawBitmap(mPersonBitmap, mDrawPixel.x - mPersonHotspot.x,
				mDrawPixel.y - mPersonHotspot.y, mPaint);
		canvas.restore();
	}
}