Java Code Examples for android.hardware.GeomagneticField

The following are top voted examples for showing how to use android.hardware.GeomagneticField. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: uds   File: QtLocation.java   View source code 6 votes vote down vote up
public void onLocationChanged(Location location)
{
    // TODO Auto-generated method stub
    double[] getData=new double[8];
    GeomagneticField geomagneticField = new GeomagneticField((float)location.getLatitude(),
            (float)location.getLongitude(), (float)location.getAltitude(),location.getTime());

    getData[0]=location.getLatitude();
    getData[1]=location.getLongitude();
    getData[2]=location.getAltitude();
    getData[3]=location.getTime();
    //these are for attributes
    getData[4]=location.getBearing();//bearing
    getData[5]=location.getSpeed();//ground speed
    getData[6]=geomagneticField.getDeclination();//magnetic dip
    getData[7]=location.getAccuracy();//vertical and horizontal accuracy

    locationDataUpdated(getData,location.getProvider());
}
 
Example 2
Project: Multiwii-Remote   File: Sensors.java   View source code 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {

	oldLocation = this.location;
	this.location = location;

	PhoneLatitude = location.getLatitude();
	PhoneLongitude = location.getLongitude();
	PhoneAltitude = location.getAltitude();
	PhoneSpeed = location.getSpeed() * 100f;
	PhoneAccuracy = location.getAccuracy() * 100f;

	//MapCurrentPosition = new LatLng(location.getLatitude(), location.getLongitude());

	geoField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(), Double.valueOf(location.getLongitude()).floatValue(), Double.valueOf(location.getAltitude()).floatValue(), System.currentTimeMillis());
	Declination = geoField.getDeclination();

	if (mGPSListener != null)
		mGPSListener.onSensorsStateGPSLocationChange();
}
 
Example 3
Project: pebble-navigation   File: WatchService.java   View source code 6 votes vote down vote up
void locationUpdate(Location currentLocation){

    	if(!currentLocation.getProvider().equals("gps")) return;
    	
    	// calculate declination at this point. This is done only once as it shouldn't change so much at similar location on earth ;)
    	//only run this if first time!
    	if (declination > 999){
    		GeomagneticField geomagneticField = new GeomagneticField((float)currentLocation.getLatitude(),
                (float)currentLocation.getLongitude(), (float)currentLocation.getAltitude(),currentLocation.getTime());
    		declination = geomagneticField.getDeclination();
    	}
    	float distance = currentLocation.distanceTo(geocacheLocation);
    	float deviceBearing = currentLocation.getBearing();
    	float azimuth = currentLocation.bearingTo(geocacheLocation);
    	if(azimuth < 0) azimuth = 360 + azimuth;
    	if(deviceBearing < 0) deviceBearing = 360 + deviceBearing;

    	float bearing = azimuth - deviceBearing;
		if(bearing < 0) bearing = 360 + bearing;
		
		updateWatchWithLocation(distance, bearing, azimuth);
    
    }
 
Example 4
Project: Military-North-Compass   File: Compass.java   View source code 5 votes vote down vote up
public void onLocationChanged(Location location) {
    mGeomagneticField = new GeomagneticField((float) location.getLatitude(),
            (float) location.getLongitude(), (float) location.getAltitude(),
            location.getTime());
    currentLocation = mProj.LL2TM2(location.getLongitude(), location.getLatitude());
    mTvGps.setText(String.format(Locale.CHINESE, "== GPS資訊 ==\n經度=%s\n緯度=%s\n橢球高=%.2f公尺\n速度=%.2f公尺/秒\n航向:%s\nTM2 E %.2f公尺, N %.2f公尺",
            Tools.Deg2DmsStr2(location.getLongitude()),
            Tools.Deg2DmsStr2(location.getLatitude()),
            location.getAltitude(),
            location.getSpeed(),
            Tools.ang2Str(location.getBearing()),
            currentLocation[0], currentLocation[1]));

    double dx = currentLocation[0] - lastX;
    double dy = currentLocation[1]  - lastY;
    if (Math.sqrt(dx*dx + dy*dy) > 1) {
        lastX = currentLocation[0]/10; lastX *= 10;
        lastY = currentLocation[1]/10; lastY *= 10;
        List<CPDB.CP> cps = cpdb.getCp(lastX, lastY, 0);
        if (cps.size() > 0) {
            String cpMsg = "鄰近控制點:\n";
            int i=0;
            for (CPDB.CP cp : cps) {
                double dx1 = cp.x - currentLocation[0], dy1 = cp.y-currentLocation[1];
                double[] resCP = Tools.POLd(dy1, dx1);
                cpMsg += String.format(Locale.CHINESE, "%s %[email protected]%d%s\n距離=%.0f公尺\n方位=%s\n",
                        cp.number, (++i), cp.t, (cp.name.length()>0?"("+cp.name+")":""),
                        resCP[0], Tools.Deg2DmsStr2(resCP[1])
                );
            }
            mTvControllPoint.setText(cpMsg);
        }
    }
}
 
Example 5
Project: Forage   File: LocationUtils.java   View source code 5 votes vote down vote up
/**
 * Gets the magnetic declination at the specified location.
 *
 * @param location Current location.
 * @return The declination of the horizontal component of the magnetic
 * field from true north, in degrees (i.e. positive means the
 * magnetic field is rotated east that much from true north).
 */
public static double getMagneticDeclination(@NonNull Location location) {
    GeomagneticField geoField = new GeomagneticField(
            (float) location.getLatitude(),
            (float) location.getLongitude(),
            (float) location.getAltitude(),
            System.currentTimeMillis()
    );

    return geoField.getDeclination();
}
 
Example 6
Project: Simple-Android-Compass-Assistant   File: CompassAssistant.java   View source code 5 votes vote down vote up
/**
 * initializes a CompassAssistant with a context and a Location. If you use this constructor the
 * resulting degrees will be calculated with the declination for the given location. The compass
 * will point to the geographic north.
 * @param context the context
 * @param l the location to which the CompassAssistant should refer its pointing.
 */
public CompassAssistant(final Context context, Location l) {
    this.context = context;

    if (l != null) {
        GeomagneticField geomagneticField = new GeomagneticField((float)l.getLatitude(),
                (float)l.getLongitude(), (float)l.getAltitude(), new Date().getTime());
        declination = geomagneticField.getDeclination();
    }

    sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

}
 
Example 7
Project: uds   File: QtLocation.java   View source code 5 votes vote down vote up
public double[] lastKnownPosition(int fromSatellitePositioningMethodsOnly)
{
    double[] getData=new double[7];
    Location location=null;
    Location networkLastLocation=null;
    Location gpsLastLocation=null;
    try
    {
        networkLastLocation=m_locationManager.getLastKnownLocation(GPS);
        gpsLastLocation=m_locationManager.getLastKnownLocation(NETWORK);
        if(fromSatellitePositioningMethodsOnly == 1)
        {
            location=gpsLastLocation;
        }
        else
        {
            location=(networkLastLocation.getTime()>gpsLastLocation.getTime())
                                                ?networkLastLocation:gpsLastLocation;
        }

        GeomagneticField geomagneticField = new GeomagneticField((float)location.getLatitude(),
                (float)location.getLongitude(), (float)location.getAltitude(),location.getTime());

        getData[0]=location.getAltitude();
        getData[1]=location.getLatitude();
        getData[2]=location.getLongitude();
        getData[3]=location.getTime();
        getData[4]=geomagneticField.getDeclination();
        getData[5]=location.getSpeed();
        getData[6]=location.getBearing();
    }
    catch(Exception e)
    {
        Log.i("QtLocation","LastknownLocation not available");
    }

    return getData;
}
 
Example 8
Project: trekarta   File: LocationInformation.java   View source code 5 votes vote down vote up
private void updateLocation(double latitude, double longitude, int zoom) {
    mLatitude = latitude;
    mLongitude = longitude;
    mZoom = zoom;

    mCoordinateDegree.setText(StringFormatter.coordinates(0, " ", latitude, longitude));
    mCoordinateDegMin.setText(StringFormatter.coordinates(1, " ", latitude, longitude));
    mCoordinateDegMinSec.setText(StringFormatter.coordinates(2, " ", latitude, longitude));
    mCoordinateUtmUps.setText(StringFormatter.coordinates(3, " ", latitude, longitude));
    mCoordinateMgrs.setText(StringFormatter.coordinates(4, " ", latitude, longitude));

    if (BuildConfig.FULL_VERSION) {
        mSunriseSunset.setLocation(latitude, longitude);
        double sunrise = mSunriseSunset.compute(true);
        double sunset = mSunriseSunset.compute(false);

        if (sunrise == Double.MAX_VALUE || sunset == Double.MAX_VALUE) {
            mSunrise.setText(R.string.never_rises);
            mSunsetTitle.setVisibility(View.GONE);
            mSunset.setVisibility(View.GONE);
        } else if (sunrise == Double.MIN_VALUE || sunset == Double.MIN_VALUE) {
            mSunset.setText(R.string.never_sets);
            mSunriseTitle.setVisibility(View.GONE);
            mSunrise.setVisibility(View.GONE);
        } else {
            mSunrise.setText(mSunriseSunset.formatTime(sunrise));
            mSunset.setText(mSunriseSunset.formatTime(sunset));
            mSunriseTitle.setVisibility(View.VISIBLE);
            mSunrise.setVisibility(View.VISIBLE);
            mSunsetTitle.setVisibility(View.VISIBLE);
            mSunset.setVisibility(View.VISIBLE);
        }

        mOffset.setText(StringFormatter.timeO((int) (mSunriseSunset.getUtcOffset() * 60)));

        GeomagneticField mag = new GeomagneticField((float) latitude, (float) longitude, 0.0f, System.currentTimeMillis());
        mDeclination.setText(String.format(Locale.getDefault(), "%+.1f\u00B0", mag.getDeclination()));
    }
}
 
Example 9
Project: stardroid   File: RealMagneticDeclinationCalculator.java   View source code 5 votes vote down vote up
/**
 * Sets the user's current location and time.
 */
@Override
public void setLocationAndTime(LatLong location, long timeInMillis) {
  geomagneticField = new GeomagneticField(location.getLatitude(),
          location.getLongitude(),
                                          0,
                                          timeInMillis);
}
 
Example 10
Project: android_maplibui   File: CompassFragment.java   View source code 5 votes vote down vote up
public static float getDeclination(Location location, long timestamp) {
    if (location == null)
        return 0;

    GeomagneticField field = new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
            (float) location.getAltitude(), timestamp);

    return field.getDeclination();
}
 
Example 11
Project: bearing-example   File: BearingToNorthProvider.java   View source code 5 votes vote down vote up
private GeomagneticField getGeomagneticField(Location location)
{
    GeomagneticField geomagneticField = new GeomagneticField(
            (float)location.getLatitude(),
            (float)location.getLongitude(),
            (float)location.getAltitude(),
            System.currentTimeMillis());
    return geomagneticField;
}
 
Example 12
Project: Artoria   File: LocationMgrImpl.java   View source code 5 votes vote down vote up
public GeomagneticField getGeomagneticField() {
	Location location = getCurrentLocation();
	GeomagneticField gmf = new GeomagneticField(
			(float) location.getLatitude(),
			(float) location.getLongitude(),
			(float) location.getAltitude(), System.currentTimeMillis());
	return gmf;
}
 
Example 13
Project: osmdroid   File: SampleHeadingCompassUp.java   View source code 5 votes vote down vote up
@Override
public void onOrientationChanged(final float orientationToMagneticNorth, IOrientationProvider source) {
    //note, on devices without a compass this never fires...

    //only use the compass bit if we aren't moving, since gps is more accurate when we are moving
    if (gpsspeed < 0.01) {
        GeomagneticField gf = new GeomagneticField(lat, lon, alt, timeOfFix);
        trueNorth = orientationToMagneticNorth + gf.getDeclination();
        gf = null;
        synchronized (trueNorth) {
            if (trueNorth > 360.0f) {
                trueNorth = trueNorth - 360.0f;
            }
            float actualHeading = 0f;

            //this part adjusts the desired map rotation based on device orientation and compass heading
            float t = (360 - trueNorth - this.deviceOrientation);
            if (t < 0) {
                t += 360;
            }
            if (t > 360) {
                t -= 360;
            }
            actualHeading = t;
            //help smooth everything out
            t = (int) t;
            t = t / 5;
            t = (int) t;
            t = t * 5;
            mMapView.setMapOrientation(t);
            updateDisplay(actualHeading,false);
        }
    }
}
 
Example 14
Project: osmLib   File: OsmAndLocationProvider.java   View source code 5 votes vote down vote up
private float calcGeoMagneticCorrection(float val) {
    if (previousCorrectionValue == 360 && getLastKnownLocation() != null) {
        OsmLocation l = getLastKnownLocation();
        GeomagneticField gf = new GeomagneticField((float) l.getLatitude(), (float) l.getLongitude(), (float) l.getAltitude(),
                System.currentTimeMillis());
        previousCorrectionValue = gf.getDeclination();
    }
    if (previousCorrectionValue != 360) {
        val += previousCorrectionValue;
    }
    return val;
}
 
Example 15
Project: fire_reporter   File: CompassFragment.java   View source code 5 votes vote down vote up
public static float getDeclination(Location location, long timestamp) {
	if(location == null)
		return 0;
	GeomagneticField field = new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
			(float) location.getAltitude(), timestamp);

	return field.getDeclination();
}
 
Example 16
Project: Androzic   File: Androzic.java   View source code 5 votes vote down vote up
@Override
public void onLocationChanged(final Location location, final boolean continous, final boolean geoid, final float smoothspeed, final float avgspeed)
{
	Log.d(TAG, "Location arrived");

	final long lastLocationMillis = location.getTime();

	if (angleMagnetic && lastLocationMillis - lastMagnetic >= magInterval)
	{
		GeomagneticField mag = new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(), (float) location.getAltitude(), System.currentTimeMillis());
		magneticDeclination = mag.getDeclination();
		lastMagnetic = lastLocationMillis;
	}

	Androzic.this.location[0] = location.getLatitude();
	Androzic.this.location[1] = location.getLongitude();

	shouldEnableFollowing = shouldEnableFollowing || lastKnownLocation == null;

	lastKnownLocation = location;
	gpsEnabled = gpsEnabled || LocationManager.GPS_PROVIDER.equals(location.getProvider());
	gpsContinous = continous;
	gpsGeoid = geoid;

	if (overlayManager.accuracyOverlay != null && location.hasAccuracy())
	{
		overlayManager.accuracyOverlay.setAccuracy(location.getAccuracy());
	}
}
 
Example 17
Project: nextgismobile_old   File: CompassFragment.java   View source code 5 votes vote down vote up
public static float getDeclination(Location location, long timestamp) {

		if(location == null){
			return 0;
		}
		GeomagneticField field = new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
				(float) location.getAltitude(), timestamp);

		return field.getDeclination();
	}
 
Example 18
Project: ARKOST   File: LocationMgrImpl.java   View source code 5 votes vote down vote up
public GeomagneticField getGeomagneticField() {
	Location location = getCurrentLocation();
	GeomagneticField gmf = new GeomagneticField(
			(float) location.getLatitude(),
			(float) location.getLongitude(),
			(float) location.getAltitude(), System.currentTimeMillis());
	return gmf;
}
 
Example 19
Project: android-compass   File: SensorsActivity.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void onLocationChanged(Location location) {
    if (location == null) throw new NullPointerException();
    currentLocation = (location);
    gmf = new GeomagneticField((float) currentLocation.getLatitude(), (float) currentLocation.getLongitude(), (float) currentLocation.getAltitude(),
            System.currentTimeMillis());
}
 
Example 20
Project: GPSTracker   File: Route.java   View source code 4 votes vote down vote up
@Override
    public void onSensorChanged(SensorEvent event) {

    // get the angle around the z-axis rotated
        if (event.sensor == mMagneticSensor) {
            System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
            mLastMagnetometerSet = true;
        } else if (event.sensor == mAccelerometer) {
            System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
            mLastAccelerometerSet = true;
        }

        if (mLastAccelerometerSet && mLastMagnetometerSet) {
            SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
            SensorManager.getOrientation(mR, mOrientation);
            float azimuthInRadians = mOrientation[0];

            float azimuthInDegress = (float) (Math.toDegrees(azimuthInRadians) + 360) % 360;

            mTargetDirection = azimuthInDegress;
        }

        float azimuth = -mTargetDirection;
        GeomagneticField geoField = new GeomagneticField( Double
                .valueOf( mLastLocation.getLatitude() ).floatValue(), Double
                .valueOf( mLastLocation.getLongitude() ).floatValue(),
                Double.valueOf( mLastLocation.getAltitude() ).floatValue(),
                System.currentTimeMillis() );
        if(geoField.getDeclination()<0) {
            azimuth += geoField.getDeclination(); // converts magnetic north into true north
        }else{
            azimuth -= geoField.getDeclination();
        }
        //Correct the azimuth
        azimuth = (azimuth+360) % 360;
        //get the bearing
        float y = (float)Math.sin(Math.toRadians(target.getLongitude()-mLastLocation.getLongitude())) * (float)Math.cos(Math.toRadians(target.getLatitude()));
        float x = (float)Math.cos(Math.toRadians(mLastLocation.getLatitude()))*(float)Math.sin(Math.toRadians(target.getLatitude())) -
                (float)Math.sin(Math.toRadians(mLastLocation.getLatitude()))*(float)Math.cos(Math.toRadians(target.getLatitude()))*(float)Math.cos(Math.toRadians(target.getLongitude()-mLastLocation.getLongitude()));
        float bearing = (float)Math.toDegrees(Math.atan2(y, x));
    image.setRotation(azimuth+bearing);
}
 
Example 21
Project: corsaire   File: NavigationService.java   View source code 4 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    Log.i(TAG, "position gps accuracy : " + location.getAccuracy());
    if (location.getAccuracy() > 30) {
        return;
    }
    this.location = location;
    Log.i(TAG, "locationChanged");
    Log.i(TAG, "distance jusqu'au prochain : " + location.distanceTo(current.end));
    Step old = current;
    current = getCurrentPoint(location);

    distance = Math.round(location.distanceTo(current.end));
    //Orientation

    GeomagneticField field = new GeomagneticField(
            (float) location.getLatitude(),
            (float) location.getLongitude(),
            (float) location.getAltitude(),
            System.currentTimeMillis()
    );

    // getDeclination returns degrees
    mDeclination = field.getDeclination();


    double lat1 = location.getLatitude();
    double lng1 = location.getLongitude();

    double lat2 = current.end.getLatitude();
    double lng2 = current.end.getLongitude();

    double dLon = (lng2 - lng1);
    double y = Math.sin(dLon) * Math.cos(lat2);
    double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    angle = Math.toDegrees((Math.atan2(y, x)));


    Calendar before = Calendar.getInstance();
    before.add(Calendar.SECOND, -40);
    if (!current.equals(old) || firstime) {
        showDirection(old);
        //showDirection();
        firstime = false;
        lastShowDirection = location;
        if(!firstime && sharedPref.getBoolean(getString(R.string.pref_vibrate_key),false) && vibrator != null){
            vibrator.vibrate(500);
        }
    } else if (lastShowDirection.distanceTo(location)>50 && (!(current instanceof TransitStep) || current.end.distanceTo(location)<100)) {
        showDirection();
        lastShowDirection = location;
    } else if (!this.arrived && current.equals(itinerary.steps.getLast()) && current.end.distanceTo(location) < 10){
        //Arrivée à destination
        this.arrived = true;
        showDirection(old);
    }
    send(UPDATE_CODE, new Bundle());

}
 
Example 22
Project: custom-maps   File: LocationTracker.java   View source code 4 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
  if (location == null || isQuitting) {
    return;
  }

  long now = System.currentTimeMillis();
  if (currentLocation != null) {
    // Never overwrite recent GPS location with a NETWORK location
    if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER) &&
        currentLocation.getProvider().equals(LocationManager.GPS_PROVIDER) &&
        now < lastGpsTime + GPS_EXPIRATION) {
      return;
    }
    // Ignore updates that come out of order from the same location provider
    if (location.getProvider().equals(currentLocation.getProvider()) &&
        location.getTime() < currentLocation.getTime()) {
      return;
    }
  }
  // Update magnetic declination once every minute
  // -- diff between "true north" and magnetic north in degrees
  if (declinationTime + 60000 < now) {
    declinationTime = now;
    GeomagneticField magneticField = new GeomagneticField(
        (float) location.getLatitude(), (float) location.getLongitude(),
        location.hasAltitude() ? (float) location.getAltitude() : 100f, // use 100m if not known
        declinationTime);
    compassDeclination = Float.valueOf(magneticField.getDeclination());
  }
  // If there is no bearing (lack of motion or network location), use latest compass heading
  if (!location.hasBearing() || !location.hasSpeed() || location.getSpeed() < 0.5f) {
    location.setBearing(compassHeading);
  }

  // Apply geoid height correction to altitude, if reported
  if (location.hasAltitude() && GeoidHeightEstimator.isInitialized()) {
    int geoidCm =
        GeoidHeightEstimator.computeGeoidHeight(location.getLatitude(), location.getLongitude());
    location.setAltitude(location.getAltitude() - Math.round(geoidCm / 100f));
  }

  // Update current location
  if (currentLocation != null) {
    currentLocation.set(location);
  } else {
    currentLocation = new Location(location);
  }

  if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
    lastGpsTime = now;
  }
  updateSpeedAndAltitude(location);
}
 
Example 23
Project: GlassNjslyr   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 24
Project: cgeo-wear   File: LocationUtils.java   View source code 4 votes vote down vote up
/**
 * Handles compass rotation.
 */
@Override
public final void onSensorChanged(SensorEvent event) {
	if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
		gravity = event.values.clone();
	} else if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
		geomagnetic = event.values.clone();
	}

	if(gravity != null && geomagnetic != null) {
		float[] R = new float[9];
		float[] I = new float[9];

		boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
		if(success) {
			final float[] orientation = new float[3];
			SensorManager.getOrientation(R, orientation);
			float azimuth = (float) (Math.toDegrees(orientation[0]) + 360) % 360;

			if(currentLocation != null) {
				final float smoothedLatitude = smoothSensorValues(
						oldLatitude, (float) currentLocation.getLatitude(), 1 / 3f);
				final float smoothedLongitude = smoothSensorValues(
						oldLongitude, (float) currentLocation.getLongitude(), 1 / 3f);
				final float smoothedAltitude = smoothSensorValues(
						oldAltitude, (float) currentLocation.getAltitude(), 1 / 3f);

				GeomagneticField geomagneticField = new GeomagneticField(
						smoothedLatitude,
						smoothedLongitude,
						smoothedAltitude,
						System.currentTimeMillis()
				);
				azimuth -= geomagneticField.getDeclination();

				final float bearing = currentLocation.bearingTo(geocacheLocation);

				final float newDirectionRaw = (360 - (azimuth-bearing)) % 360;

				final float newDirection = smoothSensorValues(oldDirection, newDirectionRaw, 1 / 5f);

				//Set old values to current values (for smoothing)
				oldDirection = newDirection;
				oldLatitude = smoothedLatitude;
				oldLongitude = smoothedLongitude;
				oldAltitude = smoothedAltitude;

				//Send direction update to Android Wear if update interval has passed
				final long currentTime = System.currentTimeMillis();
				if((currentTime - prevTime) > COMPASS_UPDATE_INTERVAL) {
					onDirectionUpdateListener.onDirectionUpdate(newDirection);
					prevTime = currentTime;
				}
			}
		}
	}
}
 
Example 25
Project: commons-android   File: SensorUtils.java   View source code 4 votes vote down vote up
public static float getLocationDeclination(Location location) {
	return new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(), (float) location.getAltitude(), location.getTime())
			.getDeclination();
}
 
Example 26
Project: casa-glass   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
	mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(), (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
			mLocation.getTime());
}
 
Example 27
Project: orientation-recorder   File: SensorsOrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 28
Project: gdk-line-sample   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 29
Project: kitty-compass   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 30
Project: SpeedHud   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 31
Project: PTVGlass   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 32
Project: PTVGlass   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 33
Project: WalkersGuide-Android   File: SensorsManager.java   View source code 4 votes vote down vote up
public void locationChanged(Location location) {
    // geomagnetic offset
    if (location.hasAltitude()) {
        GeomagneticField geoField = new GeomagneticField(
                Double.valueOf(location.getLatitude()).floatValue(),
                Double.valueOf(location.getLongitude()).floatValue(),
                Double.valueOf(location.getAltitude()).floatValue(),
                System.currentTimeMillis());
        differenceToTrueNorth = geoField.getDeclination();
    }

    // load bearing values of GPS and compass
    int bearingOfGPS = bearingOfMagneticField[0];
    if (location.hasBearing())
        bearingOfGPS = (int) location.getBearing();

    // if the application was put into background, use GPS as bearing source and remember
    // the priour bearing source, so that we can switch back imediately when the app comes
    // into foreground again
    if (globalData.applicationInBackground()) {
        if (lastBearingSource == null) {
            lastBearingSource = settingsManager.getBearingSource();
            settingsManager.setBearingSource(SettingsManager.BearingSource.GPS);
        }
    } else {
        if (lastBearingSource != null) {
            settingsManager.setBearingSource(lastBearingSource);
            lastBearingSource = null;
        }

        // check, if the diff between the location bearing value and the current compass is
        // smaller than the defined threshold
        // 0 <= diff <= 180
        int diff = Math.abs(bearingOfGPS - bearingOfMagneticField[0]);
        if (diff > 180)
            diff = 360 - diff;
        if (location.hasSpeed() && location.getSpeed() > 3.0) {
            if (diff < smallThresholdValue || diff > 180-smallThresholdValue) {
                if (matchCounter > 0)
                    matchCounter -= 1;
            } else if (diff > bigThresholdValueDrive && diff < 180-bigThresholdValueDrive) {
                if (matchCounter < maxNumberOfMatches)
                    matchCounter += 1;
            }
        } else {
            if (diff < smallThresholdValue) {
                if (matchCounter > 0)
                    matchCounter -= 1;
            } else if (diff > bigThresholdValueWalk) {
                if (matchCounter < maxNumberOfMatches)
                    matchCounter += 1;
            }
        }

        if (matchCounter == 0 && settingsManager.useGPSAsBearingSource()) {
            settingsManager.setBearingSource(SettingsManager.BearingSource.COMPASS);
            messageToast.setText(
                    mContext.getResources().getString(R.string.messageSwitchedToCompass));
            messageToast.show();
        }
        if (matchCounter == maxNumberOfMatches && settingsManager.useCompassAsBearingSource()) {
            settingsManager.setBearingSource(SettingsManager.BearingSource.GPS);
            messageToast.setText(
                    mContext.getResources().getString(R.string.messageSwitchedToGPS));
            messageToast.show();
        }
    }

    if (settingsManager.useGPSAsBearingSource()
            && bearingOfGPS != bearingOfDevice) {
        bearingOfDevice = bearingOfGPS;
        if (sListener != null)
            sListener.compassValueChanged(bearingOfDevice);
    }
}
 
Example 34
Project: Androzic   File: WaypointProject.java   View source code 4 votes vote down vote up
public void onClick(View v)
    {
    	try
    	{
    		Androzic application = Androzic.getApplication();
    		Waypoint waypoint = new Waypoint();
    		View view = getView();
    		waypoint.name = ((TextView) view.findViewById(R.id.name_text)).getText().toString();
    		double distance = Integer.parseInt(((TextView) view.findViewById(R.id.distance_text)).getText().toString());
    		double bearing = Double.parseDouble(((TextView) view.findViewById(R.id.bearing_text)).getText().toString());
    		int src = ((Spinner) view.findViewById(R.id.source_spinner)).getSelectedItemPosition();
    		int df = ((Spinner) view.findViewById(R.id.distance_spinner)).getSelectedItemPosition();
    		int bf = ((Spinner) view.findViewById(R.id.bearing_spinner)).getSelectedItemPosition();
    		double[] loc;
    		if (src > 0)
    		{
    			 loc = new double[2];
    			 loc[0] = waypoints.get(src-1).latitude;
    			 loc[1] = waypoints.get(src-1).longitude;
    		}
    		else
    		{
				loc = application.getLocation();
    		}

    		if (df == 0)
    		{
    			distance = distance / StringFormatter.distanceFactor * 1000;
    		}
    		else
    		{
    			distance = distance / StringFormatter.distanceShortFactor;
    		}
      bearing = bearing * StringFormatter.angleFactor;
    		if (bf == 1)
    		{
    			GeomagneticField mag = new GeomagneticField((float) loc[0], (float) loc[1], 0.0f, System.currentTimeMillis());
    			bearing += mag.getDeclination();
       if (bearing > 360d)
        bearing -= 360d;
    		}
    		double[] prj = Geo.projection(loc[0], loc[1], distance, bearing);
    		waypoint.latitude = prj[0];
    		waypoint.longitude = prj[1];
    		waypoint.date = Calendar.getInstance().getTime();
    		application.addWaypoint(waypoint);

    		getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
dismiss();
    	}
    	catch (Exception e)
    	{
			Toast.makeText(getActivity(), "Invalid input", Toast.LENGTH_LONG).show();
			e.printStackTrace();
    	}
    }
 
Example 35
Project: Androzic   File: Androzic.java   View source code 4 votes vote down vote up
public double getDeclination(double lat, double lon)
{
	GeomagneticField mag = new GeomagneticField((float) lat, (float) lon, 0.0f, System.currentTimeMillis());
	return mag.getDeclination();
}
 
Example 36
Project: gdk-compass-sample   File: OrientationManager.java   View source code 4 votes vote down vote up
/**
 * Updates the cached instance of the geomagnetic field after a location change.
 */
private void updateGeomagneticField() {
    mGeomagneticField = new GeomagneticField((float) mLocation.getLatitude(),
            (float) mLocation.getLongitude(), (float) mLocation.getAltitude(),
            mLocation.getTime());
}
 
Example 37
Project: Artoria   File: LocationFinder.java   View source code 2 votes vote down vote up
/**
 * 
 * @return GeomagneticField
 */
GeomagneticField getGeomagneticField();
 
Example 38
Project: ARKOST   File: LocationFinder.java   View source code 2 votes vote down vote up
/**
 * 
 * @return GeomagneticField
 */
GeomagneticField getGeomagneticField();