/** * 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; }
@Override public void onLocationChanged(Location location) { if (location.hasAccuracy()) { SpannableString s = new SpannableString(String.format("%.0f", location.getAccuracy()) + "m"); s.setSpan(new RelativeSizeSpan(0.75f), s.length() - 1, s.length(), 0); accuracy.setText(s); if (firstfix) { status.setText(""); fab.setVisibility(View.VISIBLE); if (!data.isRunning() && !maxSpeed.getText().equals("")) { refresh.setVisibility(View.VISIBLE); } firstfix = false; } } else { firstfix = true; } if (location.hasSpeed()) { progressBarCircularIndeterminate.setVisibility(View.GONE); SpannableString s = new SpannableString(String.format("%.0f", location.getSpeed() * 3.6) + "km/h"); s.setSpan(new RelativeSizeSpan(0.25f), s.length() - 4, s.length(), 0); currentSpeed.setText(s); } }
public void CalculateSpeed(LocationIdentifier previousLocation) { if (_location.hasSpeed()) _speed = _location.getSpeed(); else { double diff = (double) (getDateTime().getTime() - previousLocation.getDateTime().getTime()); double distance = _location.distanceTo(previousLocation.getLocation()); _speed = (float) (distance / diff * 3600.0); } }
ContentValues createContentValues(Waypoint waypoint) { ContentValues values = new ContentValues(); // Value < 0 indicates no id is available if (waypoint.getId() >= 0) { values.put(WaypointsColumns._ID, waypoint.getId()); } values.put(WaypointsColumns.NAME, waypoint.getName()); values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription()); values.put(WaypointsColumns.CATEGORY, waypoint.getCategory()); values.put(WaypointsColumns.ICON, waypoint.getIcon()); values.put(WaypointsColumns.TRACKID, waypoint.getTrackId()); values.put(WaypointsColumns.TYPE, waypoint.getType()); values.put(WaypointsColumns.LENGTH, waypoint.getLength()); values.put(WaypointsColumns.DURATION, waypoint.getDuration()); values.put(WaypointsColumns.STARTID, waypoint.getStartId()); values.put(WaypointsColumns.STOPID, waypoint.getStopId()); Location location = waypoint.getLocation(); if (location != null) { values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(WaypointsColumns.TIME, location.getTime()); if (location.hasAltitude()) { values.put(WaypointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasAccuracy()) { values.put(WaypointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(WaypointsColumns.SPEED, location.getSpeed()); } if (location.hasBearing()) { values.put(WaypointsColumns.BEARING, location.getBearing()); } } TripStatistics tripStatistics = waypoint.getTripStatistics(); if (tripStatistics != null) { values.put(WaypointsColumns.STARTTIME, tripStatistics.getStartTime()); values.put(WaypointsColumns.TOTALDISTANCE, tripStatistics.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, tripStatistics.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, tripStatistics.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, tripStatistics.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, tripStatistics.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, tripStatistics.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, tripStatistics.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, tripStatistics.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, tripStatistics.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, tripStatistics.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, tripStatistics.getMaxGrade()); } return values; }
private void updateNewLocation(Location location) { LocationProviderAdapter.newLocationAvailable( location.getLatitude(), location.getLongitude(), location.getTime() / 1000.0, location.hasAltitude(), location.getAltitude(), location.hasAccuracy(), location.getAccuracy(), location.hasBearing(), location.getBearing(), location.hasSpeed(), location.getSpeed()); }
@Implementation public void set(Location l) { time = l.getTime(); provider = l.getProvider(); latitude = l.getLatitude(); longitude = l.getLongitude(); accuracy = l.getAccuracy(); bearing = l.getBearing(); altitude = l.getAltitude(); speed = l.getSpeed(); hasAccuracy = l.hasAccuracy(); hasAltitude = l.hasAltitude(); hasBearing = l.hasBearing(); hasSpeed = l.hasSpeed(); }
@Override public void onLocationChanged(Location location) { // Sometimes the G1 GPS will report bogus speeds, look for really large // values float maxSpeed = 83f; // 83 m/sec is 300 km/h - i.e. really damn fast float newSpeed = Float.NaN; if (location.hasSpeed()) { newSpeed = location.getSpeed(); if (newSpeed > maxSpeed) newSpeed = Float.NaN; } float nmetersPerSec = newSpeed; if (nmetersPerSec != metersPerSec) { metersPerSec = nmetersPerSec; onChanged(); } }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static JSONObject location2Json(Location location) throws JSONException { JSONObject latLng = new JSONObject(); latLng.put("lat", location.getLatitude()); latLng.put("lng", location.getLongitude()); JSONObject params = new JSONObject(); params.put("latLng", latLng); if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { params.put("elapsedRealtimeNanos", location.getElapsedRealtimeNanos()); } else { params.put("elapsedRealtimeNanos", 0); } params.put("time", location.getTime()); /* SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); Date date = new Date(location.getTime()); params.put("timeFormatted", format.format(date)); */ if (location.hasAccuracy()) { params.put("accuracy", location.getAccuracy()); } if (location.hasBearing()) { params.put("bearing", location.getBearing()); } if (location.hasAltitude()) { params.put("altitude", location.getAltitude()); } if (location.hasSpeed()) { params.put("speed", location.getSpeed()); } params.put("provider", location.getProvider()); params.put("hashCode", location.hashCode()); return params; }
/** * Given a location fix, processes it and displays it in the table on the form. * * @param loc Location information */ private void DisplayLocationInfo(Location loc) { Utilities.LogDebug("GpsMainActivity.DisplayLocationInfo"); try { if (loc == null) { return; } TextView tvLatitude = (TextView) findViewById(R.id.txtLatitude); TextView tvLongitude = (TextView) findViewById(R.id.txtLongitude); TextView tvDateTime = (TextView) findViewById(R.id.txtDateTimeAndProvider); TextView tvAltitude = (TextView) findViewById(R.id.txtAltitude); TextView txtSpeed = (TextView) findViewById(R.id.txtSpeed); TextView txtSatellites = (TextView) findViewById(R.id.txtSatellites); TextView txtDirection = (TextView) findViewById(R.id.txtDirection); TextView txtAccuracy = (TextView) findViewById(R.id.txtAccuracy); String providerName = loc.getProvider(); if (providerName.equalsIgnoreCase("gps")) { providerName = getString(R.string.providername_gps); } else { providerName = getString(R.string.providername_celltower); } tvDateTime.setText( new Date(Session.getLatestTimeStamp()).toLocaleString() + getString(R.string.providername_using, providerName)); tvLatitude.setText(String.valueOf(loc.getLatitude())); tvLongitude.setText(String.valueOf(loc.getLongitude())); if (loc.hasAltitude()) { double altitude = loc.getAltitude(); if (AppSettings.shouldUseImperial()) { tvAltitude.setText( String.valueOf(Utilities.MetersToFeet(altitude)) + getString(R.string.feet)); } else { tvAltitude.setText(String.valueOf(altitude) + getString(R.string.meters)); } } else { tvAltitude.setText(R.string.not_applicable); } if (loc.hasSpeed()) { float speed = loc.getSpeed(); String unit; if (AppSettings.shouldUseImperial()) { if (speed > 1.47) { speed = speed * 0.6818f; unit = getString(R.string.miles_per_hour); } else { speed = Utilities.MetersToFeet(speed); unit = getString(R.string.feet_per_second); } } else { if (speed > 0.277) { speed = speed * 3.6f; unit = getString(R.string.kilometers_per_hour); } else { unit = getString(R.string.meters_per_second); } } txtSpeed.setText(String.valueOf(speed) + unit); } else { txtSpeed.setText(R.string.not_applicable); } if (loc.hasBearing()) { float bearingDegrees = loc.getBearing(); String direction; direction = Utilities.GetBearingDescription(bearingDegrees, getApplicationContext()); txtDirection.setText( direction + "(" + String.valueOf(Math.round(bearingDegrees)) + getString(R.string.degree_symbol) + ")"); } else { txtDirection.setText(R.string.not_applicable); } if (!Session.isUsingGps()) { txtSatellites.setText(R.string.not_applicable); Session.setSatelliteCount(0); } if (loc.hasAccuracy()) { float accuracy = loc.getAccuracy(); if (AppSettings.shouldUseImperial()) { txtAccuracy.setText( getString( R.string.accuracy_within, String.valueOf(Utilities.MetersToFeet(accuracy)), getString(R.string.feet))); } else { txtAccuracy.setText( getString( R.string.accuracy_within, String.valueOf(accuracy), getString(R.string.meters))); } } else { txtAccuracy.setText(R.string.not_applicable); } } catch (Exception ex) { SetStatus(getString(R.string.error_displaying, ex.getMessage())); } }
/** * 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. */ 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 }
public void onLocationChanged(Location loc) { /** * Hemos obtenido una nueva localización 1. Comprobar si es una localización válida 1.1. Que * no sea null. 1.2. Que tenga precisión suficiente. 2. Si la localización es válida. 2.1. * Enviar la localización al servidor OPEN GTS 2.2. Graba la posición en la base de datos. * 2.3. Comprobar el número de puntos en la db y si es superior a maxNumRegistrosEnDb entonces * hay que exportar los puntos al fichero de texto de la SDcard y luego borrar los registros * de la base de datos 3. Actualizar variables de "lastLocation" y los contadores de puntos * obtenidos, puntos enviados, puntos rechazados y puntos en la db 4. Enviar los datos a los * clientes UI registrados. */ // Para poder obtener la hora GregorianCalendar greg = new GregorianCalendar(TimeZone.getTimeZone("Europe/Madrid")); DateFormat timestampFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String fechaHora = timestampFormat.format(greg.getTime()); // La fecha y hora del sistema en el momento que hemos la posición // 1. Comprobar si es una localización válida // 1.1. Que no sea null. if (loc != null) { boolean pointIsRecorded = false; int cuantosRegistros; try { // 1.2. Que tenga precisión suficiente. // TODO, determinar si programamos que al estar en modo intensivo // la precisión (accuracy) se tenga que comprobar o cualquiera // nos vale // 1.2.1 Si estamos en modo intensivo, cualquier accuracy nos vale // De momento no pedimos que tenga al menos minAccuracyMeters // TODO, hay que deja el IF como sigue y quita el if (true) // if (loc.hasAccuracy() // && loc.getAccuracy() <= minAccuracyMeters) { // Para hacer debug en el emulador dejamos pasar todos los puntos if (true) { pointIsRecorded = true; // 2. Si la localización es válida. // 2.1. Enviar la localización al servidor OPEN GTS String url = "http://" + getServerName() + getGprmcName() + "acct=" + getAccountName() + "&" + "dev=" + getDeviceName() + "&" + "gprmc=" + OpenGTSutils.GPRMCEncode(loc); Log.i(tag, "URL: " + url); AsyncHttpClient client = new AsyncHttpClient(); client.get( url, new AsyncHttpResponseHandler() { @Override public void onStart() { Log.i(tag, "AsyncHttpClient onStart"); } @Override public void onSuccess(String response) { Log.i(tag, "AsyncHttpClient SUCCESS " + response); cntEnviados++; } @Override public void onFailure(Throwable e, String response) { Log.i(tag, "AsyncHttpClient FAILURE " + response); } @Override public void onFinish() { Log.i(tag, "AsyncHttpClient onFinish"); } }); // 2.2. Graba la posición en la base de datos. DbPointsManager punto = new DbPointsManager( timestampFormat.format(loc.getTime()), loc.getLatitude(), loc.getLongitude(), loc.hasAltitude() ? loc.getAltitude() : 0.0, loc.hasAccuracy() ? loc.getAccuracy() : 0.0, loc.hasSpeed() ? loc.getSpeed() : 0.0, loc.hasBearing() ? loc.getBearing() : 0.0, false); // TODO, de momento el ultimo campo "puntoEnviado", sera false, hasta que // incorporemos un sistema para poder controlar que puntos se han podido enviar // y cuales no. db.addDbPoint(punto); // Saber cuantos registros hay en la base de datos cuantosRegistros = db.getDbPointsCount(); Log.d(tag, "Reg #: " + cuantosRegistros + " Max #: " + maxNumRegistrosEnDb); // * 2.3. Comprobar el número de puntos en la db y si es superior a maxNumRegistrosEnDb // * entonces hay que exportar los puntos al fichero de texto de la SDcard y // * luego borrar los registros de la base de datos if (cuantosRegistros > maxNumRegistrosEnDb) { if (db.doDbExport(deviceName) > 0) { // * 2.3.1 Se ha exportado los datos pues ahora borrar el // * contenido de la tabla "points" de la base de datos int i; i = db.deleteDbPointAll(); Log.d(tag, "Se borraron " + i + "PUNTOS"); } } Log.i(tag, "addDbPoint: " + punto.toString()); } } catch (Exception e) { Log.e(tag, e.toString()); } finally { // Si estamos aqui algo ha ido mal así que ... /* Este código en principio no es necesario if (db.isOpen()) db.close(); */ } // Toast if (pointIsRecorded) { cntObtenidos++; /* TODO if (showingDebugToast) Toast.makeText( getBaseContext(), "Location stored: \nLat: " + sevenSigDigits.format(loc .getLatitude()) + " \nLon: " + sevenSigDigits.format(loc .getLongitude()) + " \nAlt: " + (loc.hasAltitude() ? loc .getAltitude() + "m" : "?") + "\nVel: " + (loc.hasSpeed() ? loc.getSpeed() + "m" : "?") + " \nAcc: " + (loc.hasAccuracy() ? loc .getAccuracy() + "m" : "?"), Toast.LENGTH_LONG).show(); */ } else { cntRechazados++; /* TODO if (showingDebugToast) Toast.makeText( getBaseContext(), "Location not accurate enough: \nLat: " + sevenSigDigits.format(loc .getLatitude()) + " \nLon: " + sevenSigDigits.format(loc .getLongitude()) + " \nAlt: " + (loc.hasAltitude() ? loc .getAltitude() + "m" : "?") + "\nVel: " + (loc.hasSpeed() ? loc.getSpeed() + "m" : "?") + " \nAcc: " + (loc.hasAccuracy() ? loc .getAccuracy() + "m" : "?"), Toast.LENGTH_LONG).show(); */ } } // 3. Actualizar variables de "lastLocation" y // los contadores de puntos obtenidos, puntos enviados, puntos rechazados // Poner la fecha en YYMMDD HH:MM:SS StringBuffer buf = new StringBuffer(timestampFormat.format(loc.getTime())); buf.insert(4, '-'); buf.insert(7, '-'); buf.insert(10, ' '); buf.insert(13, ':'); buf.insert(16, ':'); // buf.append('Z'); setLastDateTime(buf.toString()); setLastLatitude(String.format("%1.6f", loc.getLatitude())); setLastLongitude(String.format("%1.6f", loc.getLongitude())); setLastAccuracy((loc.hasAccuracy() ? String.format("%1.0f", loc.getAccuracy()) + "m" : "?")); setLastAltitude((loc.hasAltitude() ? String.format("%1.0f", loc.getAltitude()) + "m" : "?")); setLastSpeed((loc.hasSpeed() ? String.format("%1.0f", loc.getSpeed()) + "m/s" : "?")); setLastSpeed( getLastSpeed() + " " + (loc.hasSpeed() ? String.format("%1.0f", loc.getSpeed() * 3.6) + "km/s" : "?")); Bundle extras = loc.getExtras(); if (extras != null) { setLastSatellites( extras.containsKey("satellites") ? extras.get("satellites").toString() : "0"); Log.d(tag, "sat: " + getLastSatellites()); } else Log.d(tag, "sat: extras es null"); // Guardar el objeto de la última localización setLastLoc(loc); // Guardar el número de registros en la base de datos para luego actualizar el UI setLastPointCounter(db.getDbPointsCount()); // 4. Enviar los datos a los clientes UI registrados. sendMessageToUI(); }