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

The following examples show how to use android.location.Location#getBearing() . 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: 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 2
Source File: LocationEntity.java    From background_location_updates with Apache License 2.0 6 votes vote down vote up
public static LocationEntity fromAndroidLocation(Location location) {
    Double vAcc = null, cAcc = null, speedAcc = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vAcc = (double) location.getVerticalAccuracyMeters();
        cAcc = (double) location.getBearingAccuracyDegrees();
        speedAcc = (double) location.getSpeedAccuracyMetersPerSecond();
    }

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

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


    //use gps bearing instead of the compass

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

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

}
 
Example 4
Source File: KmlTrackWriter.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the heading to a location.
 * 
 * @param trackId the track id containing the location
 * @param location the location
 */
private float getHeading(long trackId, Location location) {
  long trackPointId = myTracksProviderUtils.getTrackPointId(trackId, location);
  if (trackPointId == -1L) {
    return location.getBearing();
  }
  Cursor cursor = null;
  Location viewLocation;
  try {
    cursor = myTracksProviderUtils.getTrackPointCursor(trackId, trackPointId, 10, true);
    if (cursor == null || cursor.getCount() == 0) {
      return location.getBearing();
    }
    cursor.moveToPosition(cursor.getCount() - 1);
    viewLocation = myTracksProviderUtils.createTrackPoint(cursor);
  } finally {
    if (cursor != null) {
      cursor.close();
    }
  }  
  return viewLocation.bearingTo(location);
}
 
Example 5
Source File: NaviEngine.java    From PocketMaps with MIT License 6 votes vote down vote up
private void calculateWrongDir(Location pos, Instruction in)
    {
      if (in.getPoints().size()<2) { return; }
      if (!wrongDir)
      {
        GeoPoint pathP1 = new GeoPoint(in.getPoints().getLat(0), in.getPoints().getLon(0));
        GeoPoint pathP2 = new GeoPoint(in.getPoints().getLat(1), in.getPoints().getLon(1));
        double bearingOk = pathP1.bearingTo(pathP2);
        double bearingCur = pos.getBearing();
        double bearingDiff = bearingOk - bearingCur;
        if (bearingDiff < 0) { bearingDiff += 360.0; } //Normalize
        if (bearingDiff > 180) { bearingDiff = 360.0 - bearingDiff; } //Normalize
        wrongDir = (bearingDiff > 100);
log("Compare bearing cur=" + bearingCur + " way=" + bearingOk + " wrong=" + wrongDir);
      }
    }
 
Example 6
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void injectBestLocation(Location location) {
    int gnssLocationFlags = LOCATION_HAS_LAT_LONG |
            (location.hasAltitude() ? LOCATION_HAS_ALTITUDE : 0) |
            (location.hasSpeed() ? LOCATION_HAS_SPEED : 0) |
            (location.hasBearing() ? LOCATION_HAS_BEARING : 0) |
            (location.hasAccuracy() ? LOCATION_HAS_HORIZONTAL_ACCURACY : 0) |
            (location.hasVerticalAccuracy() ? LOCATION_HAS_VERTICAL_ACCURACY : 0) |
            (location.hasSpeedAccuracy() ? LOCATION_HAS_SPEED_ACCURACY : 0) |
            (location.hasBearingAccuracy() ? LOCATION_HAS_BEARING_ACCURACY : 0);

    double latitudeDegrees = location.getLatitude();
    double longitudeDegrees = location.getLongitude();
    double altitudeMeters = location.getAltitude();
    float speedMetersPerSec = location.getSpeed();
    float bearingDegrees = location.getBearing();
    float horizontalAccuracyMeters = location.getAccuracy();
    float verticalAccuracyMeters = location.getVerticalAccuracyMeters();
    float speedAccuracyMetersPerSecond = location.getSpeedAccuracyMetersPerSecond();
    float bearingAccuracyDegrees = location.getBearingAccuracyDegrees();
    long timestamp = location.getTime();
    native_inject_best_location(gnssLocationFlags, latitudeDegrees, longitudeDegrees,
            altitudeMeters, speedMetersPerSec, bearingDegrees, horizontalAccuracyMeters,
            verticalAccuracyMeters, speedAccuracyMetersPerSecond, bearingAccuracyDegrees,
            timestamp);
}
 
Example 7
Source File: GpsSampleFragment.java    From genymotion-binocle with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location loc) {
    final double latitude = loc.getLatitude();
    final double longitude = loc.getLongitude();
    final double altitude = loc.getAltitude();
    final float bearing = loc.getBearing();
    final float accuracy = loc.getAccuracy();

    tvGpsCurrentLat.setText(getResources().getString(R.string.gps_currentLat, latitude));
    tvGpsCurrentLng.setText(getResources().getString(R.string.gps_currentLng, longitude));
    tvGpsCurrentAlt.setText(getResources().getString(R.string.gps_currentAltitude, altitude));
    tvGpsCurrentBearing.setText(getResources().getString(R.string.gps_currentBearing, bearing));
    tvGpsCurrentAccuracy.setText(getResources().getString(R.string.gps_currentAccuracy, accuracy));

    // Calculate distance using haversine
    double distance = GpsSampleFragment.getHaverSineDistance(latitude, longitude, DALVIK_LAT, DALVIK_LNG);
    tvGpsDistanceToDalvik.setText(getResources().getString(R.string.gps_distanceToDalvik, (int) distance));

    // Ensure labels are shown
    tvGpsCurrentLat.setVisibility(View.VISIBLE);
    tvGpsCurrentLng.setVisibility(View.VISIBLE);
    tvGpsDistanceToDalvik.setVisibility(View.VISIBLE);
    tvGpsCurrentAlt.setVisibility(View.VISIBLE);
    tvGpsCurrentBearing.setVisibility(View.VISIBLE);
    tvGpsCurrentAccuracy.setVisibility(View.VISIBLE);

    if (distance <= 100) {
        Log.d(GpsSampleFragment.TAG, "Show location warning");
        tvGpsWarning.setVisibility(View.VISIBLE);
    } else {
        Log.d(GpsSampleFragment.TAG, "Hide location warning");
        tvGpsWarning.setVisibility(View.GONE);
    }

}
 
Example 8
Source File: WeathForceActivity.java    From osmdroid with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (mMapView == null)
        return;
    //after the first fix, schedule the task to change the icon
    //mMapView.getController().setExpectedCenter(new GeoPoint(location.getLatitude(), location.getLongitude()));
    mMapView.invalidate();
    gpsbearing = location.getBearing();
    gpsspeed = location.getSpeed();
    lat = (float) location.getLatitude();
    lon = (float) location.getLongitude();
    alt = (float) location.getAltitude(); //meters
    timeOfFix = location.getTime();
}
 
Example 9
Source File: UserLocationOverlay.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void onLocationChanged(Location location, GpsLocationProvider source) {
    // If we had a previous location, let's get those bounds
    if (mLocation != null && mLocation.getBearing() == location.getBearing() && mLocation.distanceTo(location) == 0) {
        return;
    }

    updateMyLocation(location);

    synchronized (mRunOnFirstFix) {
        for (final Runnable runnable : mRunOnFirstFix) {
            new Thread(runnable).start();
        }
        mRunOnFirstFix.clear();
    }
}
 
Example 10
Source File: DirectionUtil.java    From open-location-code with Apache License 2.0 5 votes vote down vote up
/**
 * This computes a direction between {@code fromLocation} and a
 * {@code destinationCode}. The computation is done using
 * {@link Location#distanceBetween(double, double, double, double, float[])}.
 *
 * @param fromLocation    The user position.
 * @param destinationCode The code to compute the direction to.
 * @return the {@link Direction}
 */
public static Direction getDirection(Location fromLocation, OpenLocationCode destinationCode) {
    CodeArea destinationArea = destinationCode.decode();
    double toLatitude = destinationArea.getCenterLatitude();
    double toLongitude = destinationArea.getCenterLongitude();
    float[] results = new float[3];
    Location.distanceBetween(
            fromLocation.getLatitude(),
            fromLocation.getLongitude(),
            toLatitude,
            toLongitude,
            results);

    // The device bearing in the location object is 0-360, the value returned from
    // distanceBetween is -180 to 180. Adjust the device bearing to be in the same range.
    float deviceBearing = fromLocation.getBearing();
    if (deviceBearing > 180) {
        deviceBearing = deviceBearing - 360;
    }

    // Compensate the initial bearing for the device bearing.
    results[1] = results[1] - deviceBearing;
    if (results[1] > 180) {
        results[1] = -360 + results[1];
    } else if (results[1] < -180) {
        results[1] = 360 + results[1];
    }
    return new Direction(
            OpenLocationCodeUtil.createOpenLocationCode(
                    fromLocation.getLatitude(), fromLocation.getLongitude()),
            destinationCode,
            results[0],
            results[1]);
}
 
Example 11
Source File: GearService.java    From WheelLogAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onLocationChanged(Location location) {
        if(bHasSpeed = location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasAltitude = location.hasAltitude())
            mAltitude = location.getAltitude();
        if(location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasBearing = location.hasBearing())
            mBearing = location.getBearing();
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        mTime = location.getTime();
//        transmitMessage(); Me lo he llevado a la rutina que se ejecuta de forma temporizada
    }
 
Example 12
Source File: OpenLocateLocation.java    From openlocate-android with MIT License 5 votes vote down vote up
LocationInfo(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    horizontalAccuracy = location.getAccuracy();
    timeStampSecs = TimeUnit.MILLISECONDS.toSeconds(location.getTime());
    speed = location.getSpeed();
    course = location.getBearing();
    altitude = location.getAltitude();

    if (Build.VERSION.SDK_INT >= 26) {
        verticalAccuracy = location.getVerticalAccuracyMeters();
    }
}
 
Example 13
Source File: NavigationService.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
private void calculateNavigationStatus(Location loc, double smoothspeed, double avgspeed) {
    GeoPoint point = new GeoPoint(loc.getLatitude(), loc.getLongitude());
    double distance = point.vincentyDistance(navWaypoint.coordinates);
    double bearing = point.bearingTo(navWaypoint.coordinates);
    double track = loc.getBearing();

    // turn
    long turn = Math.round(bearing - track);
    if (Math.abs(turn) > 180) {
        turn = turn - (long) (Math.signum(turn)) * 360;
    }

    // vmg
    double vmg = Geo.vmg(smoothspeed, Math.abs(turn));

    // ete
    double curavvmg = Geo.vmg(avgspeed, Math.abs(turn));
    if (avvmg == 0.0 || tics % 10 == 0) {
        for (int i = vmgav.length - 1; i > 0; i--) {
            avvmg += vmgav[i];
            vmgav[i] = vmgav[i - 1];
        }
        avvmg += curavvmg;
        vmgav[0] = curavvmg;
        avvmg = avvmg / vmgav.length;
    }

    int ete = Integer.MAX_VALUE;
    if (avvmg > 0)
        ete = (int) Math.round(distance / avvmg / 60);

    double xtk = Double.NEGATIVE_INFINITY;

    if (navRoute != null) {
        boolean hasNext = hasNextRouteWaypoint();
        if (distance < navProximity) {
            if (hasNext) {
                nextRouteWaypoint();
                return;
            } else {
                updateNavigationState(STATE_REACHED);
                stopNavigation();
                return;
            }
        }

        if (prevWaypoint != null) {
            double dtk = prevWaypoint.coordinates.bearingTo(navWaypoint.coordinates);
            xtk = Geo.xtk(distance, dtk, bearing);

            if (xtk == Double.NEGATIVE_INFINITY) {
                if (mUseTraverse && hasNext) {
                    double cxtk2 = Double.NEGATIVE_INFINITY;
                    MapObject nextWpt = getNextRouteWaypoint();
                    if (nextWpt != null) {
                        double dtk2 = nextWpt.coordinates.bearingTo(navWaypoint.coordinates);
                        cxtk2 = Geo.xtk(0, dtk2, bearing);
                    }

                    if (cxtk2 != Double.NEGATIVE_INFINITY) {
                        nextRouteWaypoint();
                        return;
                    }
                }
            }
        }
    }

    tics++;

    if (distance != navDistance || bearing != navBearing || turn != navTurn || vmg != navVMG || ete != navETE || xtk != navXTK) {
        navDistance = distance;
        navBearing = bearing;
        navTurn = turn;
        navVMG = vmg;
        navETE = ete;
        navXTK = xtk;
        updateNavigationStatus();
    }
}
 
Example 14
Source File: MainActivity.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
@SuppressLint("WrongConstant")
@Override
public void onLocationChanged() {
    if (mLocationState == LocationState.SEARCHING) {
        mLocationState = mSavedLocationState;
        //TODO Change from center to location pivot (see zooming)
        mMap.getEventLayer().setFixOnCenter(true);
        updateLocationDrawable();
        mLocationOverlay.setEnabled(true);
        mMap.updateMap(true);
    }

    Location location = mLocationService.getLocation();
    double lat = location.getLatitude();
    double lon = location.getLongitude();
    float bearing = location.getBearing();
    if (bearing < mAveragedBearing - 180f)
        mAveragedBearing -= 360f;
    else if (mAveragedBearing < bearing - 180f)
        mAveragedBearing += 360f;
    mAveragedBearing = (float) movingAverage(bearing, mAveragedBearing);
    if (mAveragedBearing < 0f)
        mAveragedBearing += 360f;
    if (mAveragedBearing >= 360f)
        mAveragedBearing -= 360f;

    updateGauges();

    if (mLocationState == LocationState.NORTH || mLocationState == LocationState.TRACK) {
        long time = SystemClock.uptimeMillis();
        // Adjust map movement animation to location acquisition period to make movement smoother
        long locationDelay = time - mLastLocationMilliseconds;
        double duration = Math.min(1500, locationDelay); // 1.5 seconds maximum
        mMovementAnimationDuration = (int) movingAverage(duration, mMovementAnimationDuration);
        // Update map position
        mMap.getMapPosition(mMapPosition);

        boolean rotate = mLocationState == LocationState.TRACK && mTrackingDelay < time;
        double offset;
        if (rotate) {
            offset = mTrackingOffset / mTrackingOffsetFactor;
            if (mAutoTilt > 0f && !mAutoTiltSet && mAutoTiltShouldSet)
                mMapPosition.setTilt(mAutoTilt);
        } else {
            offset = mMovingOffset;
        }
        offset = offset / (mMapPosition.scale * Tile.SIZE);

        double rad = Math.toRadians(mAveragedBearing);
        double dx = offset * Math.sin(rad);
        double dy = offset * Math.cos(rad);

        if (!mPositionLocked) {
            mMapPosition.setX(MercatorProjection.longitudeToX(lon) + dx);
            mMapPosition.setY(MercatorProjection.latitudeToY(lat) - dy);
            mMapPosition.setBearing(-mAveragedBearing);
            //FIXME VTM
            mMap.animator().animateTo(mMovementAnimationDuration, mMapPosition, rotate);
        }
    }

    mLocationOverlay.setPosition(lat, lon, bearing);
    if (mNavigationLayer != null)
        mNavigationLayer.setPosition(lat, lon);
    mLastLocationMilliseconds = SystemClock.uptimeMillis();

    // TODO: Fix lint error
    if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_AUTO)
        checkNightMode(location);

    for (WeakReference<LocationChangeListener> weakRef : mLocationChangeListeners) {
        LocationChangeListener locationChangeListener = weakRef.get();
        if (locationChangeListener != null) {
            locationChangeListener.onLocationChanged(location);
        }
    }
}
 
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();
	}
}
 
Example 16
Source File: DebugView.java    From open with GNU General Public License v3.0 4 votes vote down vote up
private String formatBearing(Location location) {
    final float bearing = location.getBearing();
    return formatBearing(getDirectionForBearing(bearing), bearing);
}
 
Example 17
Source File: NavigationService.java    From Androzic with GNU General Public License v3.0 4 votes vote down vote up
private void calculateNavigationStatus(Location loc, float smoothspeed, float avgspeed)
{
	double distance = Geo.distance(loc.getLatitude(), loc.getLongitude(), navWaypoint.latitude, navWaypoint.longitude);
	double bearing = Geo.bearing(loc.getLatitude(), loc.getLongitude(), navWaypoint.latitude, navWaypoint.longitude);
	double track = loc.getBearing();

	// turn
	long turn = Math.round(bearing - track);
	if (Math.abs(turn) > 180)
	{
		turn = turn - (long)(Math.signum(turn))*360;
	}
	
	// vmg
	double vmg = Geo.vmg(smoothspeed, Math.abs(turn));

	// ete
	float curavvmg = (float) Geo.vmg(avgspeed, Math.abs(turn));
	if (avvmg == 0.0 || tics % 10 == 0)
	{
		for (int i = vmgav.length - 1; i > 0; i--)
		{
			avvmg += vmgav[i];
			vmgav[i] = vmgav[i - 1];
		}
		avvmg += curavvmg;
		vmgav[0] = curavvmg;
		avvmg = avvmg / vmgav.length;
	}

	int ete = Integer.MAX_VALUE;
	if (avvmg > 0)
		ete = (int) Math.round(distance / avvmg / 60);
	
	double xtk = Double.NEGATIVE_INFINITY;

	if (navRoute != null)
	{
		boolean hasNext = hasNextRouteWaypoint();
		if (distance < navProximity)
		{
			if (hasNext)
			{
				nextRouteWaypoint();
				return;
			}
			else
			{
				updateNavigationState(STATE_REACHED);
				stopNavigation();
				return;
			}
		}

		if (prevWaypoint != null)
		{
			double dtk = Geo.bearing(prevWaypoint.latitude, prevWaypoint.longitude, navWaypoint.latitude, navWaypoint.longitude);
			xtk = Geo.xtk(distance, dtk, bearing);

			if (xtk == Double.NEGATIVE_INFINITY)
			{
				if (useTraverse && hasNext)
				{
					double cxtk2 = Double.NEGATIVE_INFINITY;
					MapObject nextWpt = getNextRouteWaypoint();
					if (nextWpt != null)
					{
						double dtk2 = Geo.bearing(nextWpt.latitude, nextWpt.longitude, navWaypoint.latitude, navWaypoint.longitude);
						cxtk2 = Geo.xtk(0, dtk2, bearing);
					}

					if (cxtk2 != Double.NEGATIVE_INFINITY)
					{
						nextRouteWaypoint();
						return;
					}
				}
			}
		}
	}

	tics++;

	if (distance != navDistance || bearing != navBearing || turn != navTurn || vmg != navVMG || ete != navETE || xtk != navXTK)
	{
		navDistance = distance;
		navBearing = bearing;
		navTurn = turn;
		navVMG = vmg;
		navETE = ete;
		navXTK = xtk;
		updateNavigationStatus();
	}
}
 
Example 18
Source File: MapView.java    From Androzic with GNU General Public License v3.0 4 votes vote down vote up
public void setLocation(Location loc)
{
	currentViewport.bearing = loc.getBearing();
	currentViewport.speed = loc.getSpeed();

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

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

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

		lookAheadB = 0;
	}

	long lastLocationMillis = loc.getTime();

	if (isFollowing)
	{
		boolean newMap;
		if (bestMapEnabled && bestMapInterval > 0 && lastLocationMillis - lastBestMap >= bestMapInterval)
		{
			newMap = application.setMapCenter(currentViewport.location[0], currentViewport.location[1], true, false, loadBestMap);
			lastBestMap = lastLocationMillis;
		}
		else
		{
			newMap = application.setMapCenter(currentViewport.location[0], currentViewport.location[1], true, false, false);
			if (newMap)
				loadBestMap = bestMapEnabled;
		}
		if (newMap)
			updateMapInfo();
		updateMapCenter();
	}
	calculateVectorLength();
}
 
Example 19
Source File: GPSTesterActivityController.java    From android-gps-test-tool with Apache License 2.0 4 votes vote down vote up
private static void writeResultToTable(
			Location location,
			LocationManager locationManager,
			String elapsedTimeGPSProvider,
			Boolean isNetworkAvailable){
		
    	_gpsLatitude = location.getLatitude();
    	_gpsLongitude = location.getLongitude();
    	_gpsAccuracy = location.getAccuracy();  
    	final double speed = location.getSpeed();
    	final double altitude = location.getAltitude();

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

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