Example usage for android.hardware GeomagneticField GeomagneticField

List of usage examples for android.hardware GeomagneticField GeomagneticField

Introduction

In this page you can find the example usage for android.hardware GeomagneticField GeomagneticField.

Prototype

public GeomagneticField(float gdLatitudeDeg, float gdLongitudeDeg, float altitudeMeters, long timeMillis) 

Source Link

Document

Estimate the magnetic field at a given point and time.

Usage

From source file:Main.java

/**
 * Returns declination in degrees at given location
 * /*  www  .  j av  a 2s .c  o  m*/
 * @param location
 * @return Declination in degrees
 */
public static float getDeclinationAt(float latitude, float longitude, float altitude) {
    GeomagneticField gf = new GeomagneticField(latitude, longitude, altitude, System.currentTimeMillis());
    return gf.getDeclination();
}

From source file:com.vonglasow.michael.satstat.GpsSectionFragment.java

/**
 * Called by {@link MainActivity} when a new location is found by the GPS location provider.
 * Stores the location and updates GPS display and map view.
 *///w  ww  .  j  a v a 2 s  .  com
public void onLocationChanged(Location location) {
    if (location.hasAccuracy()) {
        Float getAcc = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAcc = (float) (location.getAccuracy());
        } else {
            getAcc = (float) (location.getAccuracy() * (float) 3.28084);
        }
        gpsAccuracy.setText(String.format("%.0f", getAcc));
        gpsAccuracyUnit
                .setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
    } else {
        gpsAccuracy.setText(getString(R.string.value_none));
        gpsAccuracyUnit.setText("");
    }

    if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_DECIMAL) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        gpsLat.setText(String.format("%.5f%s", location.getLatitude(), getString(R.string.unit_degree)));
        gpsLon.setText(String.format("%.5f%s", location.getLongitude(), getString(R.string.unit_degree)));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_MIN) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double min = 60.0 * (dec - deg);
        gpsLat.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
        dec = location.getLongitude();
        deg = (int) dec;
        min = 60.0 * (dec - deg);
        gpsLon.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_SEC) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double tmp = 60.0 * (dec - deg);
        double min = (int) tmp;
        double sec = 60.0 * (tmp - min);
        gpsLat.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
        dec = location.getLongitude();
        deg = (int) dec;
        tmp = 60.0 * (dec - deg);
        min = (int) tmp;
        sec = 60.0 * (tmp - min);
        gpsLon.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_MGRS) {
        gpsLatLayout.setVisibility(View.GONE);
        gpsLonLayout.setVisibility(View.GONE);
        gpsCoordLayout.setVisibility(View.VISIBLE);
        gpsCoord.setText(new LatLng(location.getLatitude(), location.getLongitude()).toMGRSRef()
                .toString(MGRSRef.PRECISION_1M));
    }
    if (mainActivity.prefUtc)
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
    else
        df.setTimeZone(TimeZone.getDefault());
    gpsTime.setText(df.format(new Date(location.getTime())));

    if (location.hasAltitude()) {
        Float getAltitude = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAltitude = (float) (location.getAltitude());
        } else {
            getAltitude = (float) (location.getAltitude() * (float) 3.28084);
        }
        gpsAlt.setText(String.format("%.0f", getAltitude));
        gpsAltUnit.setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
        orDeclination.setText(String.format("%.0f%s",
                new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
                        (float) (getAltitude), location.getTime()).getDeclination(),
                getString(R.string.unit_degree)));
    } else {
        gpsAlt.setText(getString(R.string.value_none));
        gpsAltUnit.setText("");
        orDeclination.setText(getString(R.string.value_none));
    }

    if (location.hasBearing()) {
        gpsBearing.setText(String.format("%.0f%s", location.getBearing(), getString(R.string.unit_degree)));
        gpsOrientation.setText(MainActivity.formatOrientation(this.getContext(), location.getBearing()));
    } else {
        gpsBearing.setText(getString(R.string.value_none));
        gpsOrientation.setText(getString(R.string.value_none));
    }

    if (location.hasSpeed()) {
        Float getSpeed = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getSpeed = (float) (location.getSpeed() * 3.6f);
        } else {
            getSpeed = (float) (location.getSpeed() * 3.6f * 2.23694f);
        }
        gpsSpeed.setText(String.format("%.0f", getSpeed));
        gpsSpeedUnit.setText(getString(((mainActivity.prefUnitType) ? R.string.unit_km_h : R.string.unit_mph)));
    } else {
        gpsSpeed.setText(getString(R.string.value_none));
        gpsSpeedUnit.setText("");
    }

    // note: getting number of sats in fix by looking for "satellites"
    // in location's extras doesn't seem to work, always returns 0 sats
}

From source file:com.vonglasow.michael.satstat.ui.GpsSectionFragment.java

/**
 * Called by {@link MainActivity} when a new location is found by the GPS location provider.
 * Stores the location and updates GPS display and map view.
 *///from  w  w w  .  jav  a2s  .  c  o  m
public void onLocationChanged(Location location) {
    if (location.hasAccuracy()) {
        Float getAcc = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAcc = (float) (location.getAccuracy());
        } else {
            getAcc = (float) (location.getAccuracy() * (float) 3.28084);
        }
        gpsAccuracy.setText(String.format("%.0f", getAcc));
        gpsAccuracyUnit
                .setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
    } else {
        gpsAccuracy.setText(getString(R.string.value_none));
        gpsAccuracyUnit.setText("");
    }

    if (mainActivity.prefCoord == Const.KEY_PREF_COORD_DECIMAL) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        gpsLat.setText(String.format("%.5f%s", location.getLatitude(), getString(R.string.unit_degree)));
        gpsLon.setText(String.format("%.5f%s", location.getLongitude(), getString(R.string.unit_degree)));
    } else if (mainActivity.prefCoord == Const.KEY_PREF_COORD_MIN) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double min = 60.0 * (dec - deg);
        gpsLat.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
        dec = location.getLongitude();
        deg = (int) dec;
        min = 60.0 * (dec - deg);
        gpsLon.setText(
                String.format("%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
    } else if (mainActivity.prefCoord == Const.KEY_PREF_COORD_SEC) {
        gpsCoordLayout.setVisibility(View.GONE);
        gpsLatLayout.setVisibility(View.VISIBLE);
        gpsLonLayout.setVisibility(View.VISIBLE);
        double dec = location.getLatitude();
        double deg = (int) dec;
        double tmp = 60.0 * (dec - deg);
        double min = (int) tmp;
        double sec = 60.0 * (tmp - min);
        gpsLat.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
        dec = location.getLongitude();
        deg = (int) dec;
        tmp = 60.0 * (dec - deg);
        min = (int) tmp;
        sec = 60.0 * (tmp - min);
        gpsLon.setText(String.format("%.0f%s %.0f' %.1f\"", deg, getString(R.string.unit_degree), min,
                sec + /*rounding*/ 0.05));
    } else if (mainActivity.prefCoord == Const.KEY_PREF_COORD_MGRS) {
        gpsLatLayout.setVisibility(View.GONE);
        gpsLonLayout.setVisibility(View.GONE);
        gpsCoordLayout.setVisibility(View.VISIBLE);
        gpsCoord.setText(new LatLng(location.getLatitude(), location.getLongitude()).toMGRSRef()
                .toString(MGRSRef.PRECISION_1M));
    }
    if (mainActivity.prefUtc)
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
    else
        df.setTimeZone(TimeZone.getDefault());
    gpsTime.setText(df.format(new Date(location.getTime())));

    if (location.hasAltitude()) {
        Float getAltitude = (float) 0.0;
        if (mainActivity.prefUnitType) {
            getAltitude = (float) (location.getAltitude());
        } else {
            getAltitude = (float) (location.getAltitude() * (float) 3.28084);
        }
        gpsAlt.setText(String.format("%.0f", getAltitude));
        gpsAltUnit.setText(getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
        orDeclination.setText(String.format("%.0f%s",
                new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
                        (float) (getAltitude), location.getTime()).getDeclination(),
                getString(R.string.unit_degree)));
    } else {
        gpsAlt.setText(getString(R.string.value_none));
        gpsAltUnit.setText("");
        orDeclination.setText(getString(R.string.value_none));
    }

    if (location.hasBearing()) {
        gpsBearing.setText(String.format("%.0f%s", location.getBearing(), getString(R.string.unit_degree)));
        gpsOrientation.setText(MainActivity.formatOrientation(this.getContext(), location.getBearing()));
    } else {
        gpsBearing.setText(getString(R.string.value_none));
        gpsOrientation.setText(getString(R.string.value_none));
    }

    if (location.hasSpeed()) {
        Float getSpeed = (float) 0.0;
        if (mainActivity.prefKnots) {
            getSpeed = (float) (location.getSpeed() * 1.943844f);
        } else if (mainActivity.prefUnitType) {
            getSpeed = (float) (location.getSpeed() * 3.6f);
        } else {
            getSpeed = (float) (location.getSpeed() * 2.23694f);
        }
        gpsSpeed.setText(String.format("%.0f", getSpeed));
        gpsSpeedUnit.setText(getString(((mainActivity.prefKnots) ? R.string.unit_kn
                : (mainActivity.prefUnitType) ? R.string.unit_km_h : R.string.unit_mph)));
    } else {
        gpsSpeed.setText(getString(R.string.value_none));
        gpsSpeedUnit.setText("");
    }

    // note: getting number of sats in fix by looking for "satellites"
    // in location's extras doesn't seem to work, always returns 0 sats
}

From source file:com.nextgis.mobile.forms.CompassFragment.java

public static float getDeclination(Location location, long timestamp) {

    if (location == null) {
        return 0;
    }//from  w  w w .ja v a 2s .c o  m
    GeomagneticField field = new GeomagneticField((float) location.getLatitude(),
            (float) location.getLongitude(), (float) location.getAltitude(), timestamp);

    return field.getDeclination();
}

From source file:com.nextgis.maplibui.fragment.CompassFragment.java

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

From source file:com.javadog.cgeowear.cgeoWear.java

/**
 * Interprets watch compass if user has requested that feature.
 *//*from   www.j  a v  a2s.com*/
@Override
public 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(); //TODO: Some watches don't let me access the compass correctly yet.
    }

    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) {
            float[] orientation = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimuth = (float) Math.toDegrees(orientation[0]);

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

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

                float bearing = currentLocation.bearingTo(geocacheLocation);

                direction = smoothSensorValues(oldDirection, -(azimuth - bearing), 1 / 5f);

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

                //Display direction on compass if update interval has passed
                long currentTime = System.currentTimeMillis();
                if ((currentTime - prevTime) > DIRECTION_UPDATE_SPEED) {
                    rotateCompass(direction);
                    prevTime = currentTime;
                }
            }
        }
    }
}

From source file:com.example.hciproject.CameraActivity.java

private void processLocation(Location location) {
    Log.d("LOCATION", "lat:" + location.getLatitude() + "long:" + location.getLongitude());

    String result;//w w  w. ja v a2 s .  c  o  m
    if (Xlat > location.getLatitude()) {
        //0-180
        if (Xlong > location.getLongitude()) {
            //0-90
            moires = 90;
        } else {
            //90-180
            moires = 180;
        }
    } else {
        //180-360
        if (Xlong > location.getLongitude()) {
            //180-270
            moires = 270;
        } else {
            //270-360
            moires = 360;
        }
    }

    if (location.getLatitude() < Xlat) {
        result = "PISW SOU";
        if (location.getLongitude() < Xlong) {
            result = result + " ARISTERA";
        } else {
            result = result + " DEKSIA";
        }
    } else {
        result = "MPROSTA SOU";
        if (location.getLongitude() < Xlong) {
            result = result + " ARISTERA";
        } else {
            result = result + " DEKSIA";
        }
    }

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

    Log.d("STORE", result);
}

From source file:com.javadog.cgeowear.WearService.java

/**
 * Handles compass rotation.//from   w w  w  . j  ava  2s.  com
 */
@Override
public 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) {
            float[] orientation = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimuth = (float) Math.toDegrees(orientation[0]);
            float pitch = (float) Math.toDegrees(orientation[1]);

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

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

                float bearing = currentLocation.bearingTo(geocacheLocation);

                float direction = smoothSensorValues(oldDirection, -(azimuth - bearing), 1 / 5f);

                //If the user puts the phone in his/her pocket upside-down, invert the compass
                if (pitch > 0) {
                    direction += 180f;
                }

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

                //Send direction update to Android Wear if update interval has passed
                long currentTime = System.currentTimeMillis();
                if ((currentTime - prevTime) > DIRECTION_UPDATE_SPEED) {
                    wearInterface.sendDirectionUpdate(direction);
                    prevTime = currentTime;
                }
            }
        }
    }
}

From source file:uk.org.rivernile.edinburghbustracker.android.fragments.general.BusStopDetailsFragment.java

/**
 * {@inheritDoc}/* w  w  w . j  a v a 2s. com*/
 */
@Override
public void onLocationChanged(final Location location) {
    if (LocationUtils.isBetterLocation(location, lastLocation)) {
        lastLocation = location;

        // Calculate the GeomagneticField of the current location. This is
        // used by the direction indicator.
        if (location != null) {
            geoField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(),
                    Double.valueOf(location.getLongitude()).floatValue(),
                    Double.valueOf(location.getAltitude()).floatValue(), System.currentTimeMillis());
        }

        updateLocation();
    }
}

From source file:gov.nasa.arc.geocam.geocam.GeoCamService.java

void postProcessLocation(Uri uri) {
    final String[] projection = new String[] { MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images.ImageColumns.LATITUDE,
            MediaStore.Images.ImageColumns.LONGITUDE, MediaStore.Images.ImageColumns.DESCRIPTION,
            MediaStore.Images.ImageColumns.SIZE, };

    try {//from   w ww .  j  a v a  2 s .c  o m
        Cursor cur = getContentResolver().query(uri, projection, null, null, null);
        cur.moveToFirst();

        long dateTakenMillis = cur.getLong(cur.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN));
        String imageData = cur.getString(cur.getColumnIndex(MediaStore.Images.ImageColumns.DESCRIPTION));
        cur.close();

        List<Location> points = mGpsLog.getBoundingLocations(dateTakenMillis, 1);
        if (points.size() == 2) {
            Location before = points.get(0);
            Location after = points.get(1);
            double lat, lon, alt;

            long beforeDiff = dateTakenMillis - before.getTime();
            long afterDiff = after.getTime() - dateTakenMillis;
            long diff = beforeDiff + afterDiff;

            if (diff < GeoCamMobile.PHOTO_BRACKET_INTERVAL_MSECS) {
                // best case -- not too much time lag between bracketing positions. interpolate.
                double a = ((double) beforeDiff) / diff;
                lat = before.getLatitude() + a * (after.getLatitude() - before.getLatitude());
                lon = before.getLongitude() + a * (after.getLongitude() - before.getLongitude());
                alt = before.getAltitude() + a * (after.getAltitude() - before.getLongitude());
            } else if (beforeDiff < GeoCamMobile.PHOTO_BRACKET_THRESHOLD_MSECS
                    || afterDiff < GeoCamMobile.PHOTO_BRACKET_THRESHOLD_MSECS) {
                // one of the two points is close enough in time to the photo capture time. use its position.
                if (beforeDiff < afterDiff) {
                    lat = before.getLatitude();
                    lon = before.getLongitude();
                    alt = before.getAltitude();
                } else {
                    lat = after.getLatitude();
                    lon = after.getLongitude();
                    alt = after.getAltitude();
                }
            } else {
                // otherwise, we don't have any usable position data
                lat = 0.0;
                lon = 0.0;
                alt = 0.0;
            }

            // Fix the geomagnetic declination if we have all of our info
            if (!(lat == 0.0 && lon == 0.0 && alt == 0.0)) {
                GeomagneticField field = new GeomagneticField((float) lat, (float) lon, (float) alt,
                        dateTakenMillis);
                float declination = field.getDeclination();

                try {
                    JSONObject dataObj = new JSONObject(imageData);

                    double[] angles = GeoCamMobile.rpyUnSerialize(dataObj.getString("rpy"));
                    angles[2] += declination;
                    Log.d(GeoCamMobile.DEBUG_ID,
                            "Fixed heading. Declination: " + declination + " New heading: " + angles[2]);

                    dataObj.put("rpy", GeoCamMobile.rpySerialize(angles[0], angles[1], angles[2]));
                    dataObj.put("yawRef", GeoCamMobile.YAW_TRUE);

                    imageData = dataObj.toString();
                } catch (JSONException e) {
                    Log.e(GeoCamMobile.DEBUG_ID, "Error decoding/encoding for geomagnetic stuff" + e);
                }
            }

            ContentValues values = new ContentValues(2);
            values.put(MediaStore.Images.ImageColumns.LATITUDE, lat);
            values.put(MediaStore.Images.ImageColumns.LONGITUDE, lon);
            values.put(MediaStore.Images.ImageColumns.DESCRIPTION, imageData);
            getContentResolver().update(uri, values, null, null);
        }
    } catch (CursorIndexOutOfBoundsException e) {

    }
}