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

The following examples show how to use android.location.Location#setAltitude() . 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: LocationService.java    From FineGeotag with GNU General Public License v3.0 6 votes vote down vote up
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jObject = (JsonObject) json;
    Location location = new Location(jObject.get("Provider").getAsString());

    location.setTime(jObject.get("Time").getAsLong());
    location.setLatitude(jObject.get("Latitude").getAsDouble());
    location.setLongitude(jObject.get("Longitude").getAsDouble());

    if (jObject.has("Altitude"))
        location.setAltitude(jObject.get("Altitude").getAsDouble());

    if (jObject.has("Speed"))
        location.setSpeed(jObject.get("Speed").getAsFloat());

    if (jObject.has("Bearing"))
        location.setBearing(jObject.get("Bearing").getAsFloat());

    if (jObject.has("Accuracy"))
        location.setAccuracy(jObject.get("Accuracy").getAsFloat());

    return location;
}
 
Example 2
Source File: DataUploadServiceTest.java    From open with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldHaveSpeedElement() throws Exception {
    String expectedSpeed = "40.0";
    String groupId = "test-group-id";
    String routeId = "test-route-id";
    fillLocationsTable(groupId, routeId, 10, true);
    Location loc = getTestLocation(100, 200);
    loc.setBearing(4.0f);
    loc.setSpeed(Float.valueOf(expectedSpeed));
    loc.setAccuracy(12f);
    loc.setAltitude(12f);
    loc.setTime(System.currentTimeMillis());
    ContentValues insertValues = valuesForLocationCorrection(loc, loc, getTestInstruction(0, 0),
        routeId);
    db.insert(TABLE_LOCATIONS, null, insertValues);

    String actual = getTextForXpath(groupId,
            "//trk/trkseg/trkpt[position()=last()]/speed/text()");

    assertThat(actual).isEqualTo(expectedSpeed);
}
 
Example 3
Source File: LocationFactory.java    From io.appium.settings with Apache License 2.0 6 votes vote down vote up
public synchronized Location createLocation(String providerName, float accuracy) {
    Location l = new Location(providerName);
    l.setAccuracy(accuracy);

    l.setLatitude(latitude);
    l.setLongitude(longitude);
    l.setAltitude(altitude);
    l.setSpeed(0);
    l.setBearing(0);

    l.setTime(System.currentTimeMillis());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        l.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    return l;
}
 
Example 4
Source File: ReplayJsonRouteLocationMapper.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
private List<Location> mapReplayLocations() {
  List<Location> locations = new ArrayList<>(replayLocations.size());
  for (ReplayLocationDto sample : replayLocations) {
    Location location = new Location(REPLAY);
    location.setLongitude(sample.getLongitude());
    location.setAccuracy(sample.getHorizontalAccuracyMeters());
    location.setBearing((float) sample.getBearing());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      location.setVerticalAccuracyMeters(sample.getVerticalAccuracyMeters());
    }
    location.setSpeed((float) sample.getSpeed());
    location.setLatitude(sample.getLatitude());
    location.setAltitude(sample.getAltitude());
    Date date = sample.getDate();
    if (date != null) {
      location.setTime(date.getTime());
    }
    locations.add(location);
  }
  return locations;
}
 
Example 5
Source File: Sensors.java    From Multiwii-Remote with Apache License 2.0 6 votes vote down vote up
public void setMOCKLocation(double Latitude, double Longitude, float Altitude, float Heading, float speed) {

		Location mockLocation = new Location(mocLocationProvider); // a string
		mockLocation.setLatitude(Latitude); // double
		mockLocation.setLongitude(Longitude);
		mockLocation.setAltitude(Altitude);
		mockLocation.setTime(System.currentTimeMillis());
		mockLocation.setAccuracy(1);
		mockLocation.setBearing(Heading);
		mockLocation.setSpeed(speed * 0.01f);

		try {
			Method locationJellyBeanFixMethod = Location.class.getMethod("makeComplete");
			if (locationJellyBeanFixMethod != null) {
				locationJellyBeanFixMethod.invoke(mockLocation);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		locationManager.setTestProviderLocation(mocLocationProvider, mockLocation);

	}
 
Example 6
Source File: BackgroundLocation.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
/**
 * Return android Location instance
 *
 * @return android.location.Location instance
 */
public Location getLocation() {
    Location l = new Location(provider);
    l.setLatitude(latitude);
    l.setLongitude(longitude);
    l.setTime(time);
    if (hasAccuracy) l.setAccuracy(accuracy);
    if (hasAltitude) l.setAltitude(altitude);
    if (hasSpeed) l.setSpeed(speed);
    if (hasBearing) l.setBearing(bearing);
    l.setExtras(extras);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        l.setElapsedRealtimeNanos(elapsedRealtimeNanos);
    }

    return l;
}
 
Example 7
Source File: GenerateGPX.java    From PocketMaps with MIT License 5 votes vote down vote up
public ArrayList<Location> readGpxFile(File gpxFile) throws IOException, ParserConfigurationException, SAXException, ParseException
{
  ArrayList<Location> posList = new ArrayList<Location>();
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(gpxFile);
  doc.getDocumentElement().normalize();
  NodeList nList = doc.getElementsByTagName("trkpt");
  for (int i = 0; i < nList.getLength(); i++)
  {
    Node node = nList.item(i);
    System.out.println("Current Element :" + node.getNodeName());
        
    if (node.getNodeType() == Node.ELEMENT_NODE)
    {
      Element element = (Element) node;
      log("--> Tracking-Element: " + element.getTagName());
      log("--> Tracking-Lat: " + element.getAttribute("lat"));
      double lat = Double.parseDouble(element.getAttribute("lat"));
      log("--> Tracking-Lon: " + element.getAttribute("lon"));
      double lon = Double.parseDouble(element.getAttribute("lon"));
      Node eleN = element.getElementsByTagName("ele").item(0);
      log("--> Tracking-ele: " + eleN.getTextContent());
      double ele = Double.parseDouble(eleN.getTextContent());
      Node timeN = element.getElementsByTagName("time").item(0);
      String timeS = timeN.getTextContent();
      log("--> Tracking-time: " + timeS);
      Date timeD = DF.parse(timeS);
      log("--> Tracking-time: " + timeD.getTime());
      Location location = new Location("com.junjunguo.pocketmaps");
      location.setLatitude(lat);
      location.setLongitude(lon);
      location.setAltitude(ele);
      location.setTime(timeD.getTime());
      posList.add(location);
    }
  }
  return posList;
}
 
Example 8
Source File: ARPoint.java    From ar-location-based-android with MIT License 5 votes vote down vote up
public ARPoint(String name, double lat, double lon, double altitude) {
    this.name = name;
    location = new Location("ARPoint");
    location.setLatitude(lat);
    location.setLongitude(lon);
    location.setAltitude(altitude);
}
 
Example 9
Source File: MyTracksProviderUtilsImpl.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Fills a track point from a cursor.
 * 
 * @param cursor the cursor pointing to a location.
 * @param indexes the cached track points indexes
 * @param location the track point
 */
private void fillTrackPoint(Cursor cursor, CachedTrackPointsIndexes indexes, Location location) {
  location.reset();

  if (!cursor.isNull(indexes.longitudeIndex)) {
    location.setLongitude(((double) cursor.getInt(indexes.longitudeIndex)) / 1E6);
  }
  if (!cursor.isNull(indexes.latitudeIndex)) {
    location.setLatitude(((double) cursor.getInt(indexes.latitudeIndex)) / 1E6);
  }
  if (!cursor.isNull(indexes.timeIndex)) {
    location.setTime(cursor.getLong(indexes.timeIndex));
  }
  if (!cursor.isNull(indexes.altitudeIndex)) {
    location.setAltitude(cursor.getFloat(indexes.altitudeIndex));
  }
  if (!cursor.isNull(indexes.accuracyIndex)) {
    location.setAccuracy(cursor.getFloat(indexes.accuracyIndex));
  }
  if (!cursor.isNull(indexes.speedIndex)) {
    location.setSpeed(cursor.getFloat(indexes.speedIndex));
  }
  if (!cursor.isNull(indexes.bearingIndex)) {
    location.setBearing(cursor.getFloat(indexes.bearingIndex));
  }
  if (location instanceof MyTracksLocation && !cursor.isNull(indexes.sensorIndex)) {
    MyTracksLocation myTracksLocation = (MyTracksLocation) location;
    try {
      myTracksLocation.setSensorDataSet(
          SensorDataSet.parseFrom(cursor.getBlob(indexes.sensorIndex)));
    } catch (InvalidProtocolBufferException e) {
      Log.w(TAG, "Failed to parse sensor data.", e);
    }
  }
}
 
Example 10
Source File: MockLocationProvider.java    From FakeTraveler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Pushes the location in the system (mock). This is where the magic gets done.
 *
 * @param lat latitude
 * @param lon longitude
 * @return Void
 */
public void pushLocation(double lat, double lon) {
    LocationManager lm = (LocationManager) ctx.getSystemService(
            Context.LOCATION_SERVICE);

    Location mockLocation = new Location(providerName);
    mockLocation.setLatitude(lat);
    mockLocation.setLongitude(lon);
    mockLocation.setAltitude(3F);
    mockLocation.setTime(System.currentTimeMillis());
    //mockLocation.setAccuracy(16F);
    mockLocation.setSpeed(0.01F);
    mockLocation.setBearing(1F);
    mockLocation.setAccuracy(3F);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setBearingAccuracyDegrees(0.1F);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setVerticalAccuracyMeters(0.1F);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setSpeedAccuracyMetersPerSecond(0.01F);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    lm.setTestProviderLocation(providerName, mockLocation);
}
 
Example 11
Source File: SQLiteLocationDAOTest.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
@Test
public void persistLocation() {
    Context ctx = InstrumentationRegistry.getTargetContext();
    SQLiteDatabase db = new SQLiteOpenHelper(ctx).getWritableDatabase();
    SQLiteLocationDAO dao = new SQLiteLocationDAO(db);

    Location location = new Location("fake");
    location.setAccuracy(200);
    location.setAltitude(900);
    location.setBearing(2);
    location.setLatitude(40.21);
    location.setLongitude(23.45);
    location.setSpeed(20);
    location.setProvider("test");
    location.setTime(1000);
    BackgroundLocation bgLocation = new BackgroundLocation(location);

    dao.persistLocation(bgLocation);

    ArrayList<BackgroundLocation> locations = new ArrayList(dao.getAllLocations());
    Assert.assertEquals(1, locations.size());

    BackgroundLocation storedLocation = locations.get(0);
    Assert.assertEquals(200, storedLocation.getAccuracy(), 0);
    Assert.assertEquals(900, storedLocation.getAltitude(), 0);
    Assert.assertEquals(2, storedLocation.getBearing(), 0);
    Assert.assertEquals(40.21, storedLocation.getLatitude(), 0);
    Assert.assertEquals(23.45, storedLocation.getLongitude(), 0);
    Assert.assertEquals(20, storedLocation.getSpeed(), 0);
    Assert.assertEquals("test", storedLocation.getProvider(), "test");
    Assert.assertEquals(1000, storedLocation.getTime(), 0);
    Assert.assertFalse(storedLocation.hasMockLocationsEnabled());
    Assert.assertFalse(storedLocation.areMockLocationsEnabled());
    Assert.assertTrue(storedLocation.hasIsFromMockProvider()); // because setIsFromMockProvider is called in constructor
    Assert.assertFalse(storedLocation.isFromMockProvider());
}
 
Example 12
Source File: SendFusionTablesUtilsTest.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a valid
 * point.
 */
public void testGetKmlPoint_valid_point() {
  Location location = new Location("test");
  location.setLongitude(10.1);
  location.setLatitude(20.2);
  location.setAltitude(30.3);
  assertEquals("<Point><coordinates>10.1,20.2,30.3</coordinates></Point>",
      SendFusionTablesUtils.getKmlPoint(location));
}
 
Example 13
Source File: MyTracksProviderUtilsImplTest.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a location.
 * @param i the index to set the value of location.
 * @return created location
 */
private Location createLocation(int i) {
  
  Location loc = new Location("test");
  loc.setLatitude(INITIAL_LATITUDE + (double) i / 10000.0);
  loc.setLongitude(INITIAL_LONGITUDE - (double) i / 10000.0);
  loc.setAccuracy((float) i / 100.0f);
  loc.setAltitude(i * ALTITUDE_INTERVAL);
  return loc;
}
 
Example 14
Source File: MockLocationProvider.java    From android_coursera_1 with MIT License 5 votes vote down vote up
public void pushLocation(double lat, double lon) {

		Location mockLocation = new Location(mProviderName);
		mockLocation.setLatitude(lat);
		mockLocation.setLongitude(lon);
		mockLocation.setAltitude(0);
		mockLocation.setTime(System.currentTimeMillis());
		mockLocation
				.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
		mockLocation.setAccuracy(mockAccuracy);

		mLocationManager.setTestProviderLocation(mProviderName, mockLocation);

	}
 
Example 15
Source File: MockLocationProvider.java    From android_coursera_1 with MIT License 5 votes vote down vote up
public void pushLocation(double lat, double lon) {

		Location mockLocation = new Location(mProviderName);
		mockLocation.setLatitude(lat);
		mockLocation.setLongitude(lon);
		mockLocation.setAltitude(0);
		mockLocation.setTime(System.currentTimeMillis());
		mockLocation
				.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
		mockLocation.setAccuracy(mockAccuracy);

		mLocationManager.setTestProviderLocation(mProviderName, mockLocation);

	}
 
Example 16
Source File: MockLocationProvider.java    From mockgeofix with Apache License 2.0 5 votes vote down vote up
protected void _simulate(double longitude, double latitude, double altitude, int satellites) {
    Location mockLocation = new Location(locationProviderName); // a string
    mockLocation.setLatitude(latitude);  // double
    mockLocation.setLongitude(longitude);
    mockLocation.setAltitude(altitude);
    if (satellites != -1) {
        Bundle bundle = new Bundle();
        bundle.putInt("satellites", satellites);
        mockLocation.setExtras(bundle);
    }
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setAccuracy(accuracy);
    _simulate(mockLocation);
}
 
Example 17
Source File: AbstractTestFileTrackImporter.java    From mytracks with Apache License 2.0 5 votes vote down vote up
protected Location createLocation(int index, long time) {
  Location location = new Location(LocationManager.GPS_PROVIDER);
  location.setLatitude(TRACK_LATITUDE + index);
  location.setLongitude(TRACK_LONGITUDE + index);
  location.setAltitude(TRACK_ELEVATION + index);
  location.setTime(time);
  return location;
}
 
Example 18
Source File: MyTracksProviderUtilsImplTest.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the method {@link MyTracksProviderUtilsImpl#createContentValues(Waypoint)}.
 */
public void testCreateContentValues_waypoint() {
  long trackId = System.currentTimeMillis();
  Track track = getTrack(trackId, 10);
  providerUtils.insertTrack(track);
  // Bottom
  long startTime = 1000L;
  // AverageSpeed
  double minGrade = -20.11;
  TripStatistics statistics = new TripStatistics();
  statistics.setStartTime(startTime);
  statistics.setStopTime(2500L);
  statistics.setTotalTime(1500L);
  statistics.setMovingTime(700L);
  statistics.setTotalDistance(750.0);
  statistics.setTotalElevationGain(50.0);
  statistics.setMaxSpeed(60.0);
  statistics.setMaxElevation(1250.0);
  statistics.setMinElevation(1200.0);
  statistics.setMaxGrade(15.0);
  statistics.setMinGrade(minGrade);
  statistics.setBounds(-10000, 20000, 30000, -40000);
  // Insert at first.
  Waypoint waypoint = new Waypoint();
  waypoint.setDescription(TEST_DESC);
  waypoint.setType(WaypointType.STATISTICS);
  waypoint.setTripStatistics(statistics);
  
  Location loc = new Location("test");
  loc.setLatitude(22);
  loc.setLongitude(22);
  loc.setAccuracy((float) 1 / 100.0f);
  loc.setAltitude(2.5);
  waypoint.setLocation(loc);
  providerUtils.insertWaypoint(waypoint);

  MyTracksProviderUtilsImpl myTracksProviderUtilsImpl = new MyTracksProviderUtilsImpl(
      new MockContentResolver());
  
  long waypointId = System.currentTimeMillis();
  waypoint.setId(waypointId);
  ContentValues contentValues = myTracksProviderUtilsImpl.createContentValues(waypoint);
  assertEquals(waypointId, contentValues.get(WaypointsColumns._ID));
  assertEquals(22 * 1000000, contentValues.get(WaypointsColumns.LONGITUDE));
  assertEquals(TEST_DESC, contentValues.get(WaypointsColumns.DESCRIPTION));
  assertEquals(startTime, contentValues.get(WaypointsColumns.STARTTIME));
  assertEquals(minGrade, contentValues.get(WaypointsColumns.MINGRADE));
}
 
Example 19
Source File: LocationServiceTest.java    From background-geolocation-android with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 5000)
public void testOnLocationOnStoppedService() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(3);
    BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            int action = bundle.getInt("action");

            if (action == LocationServiceImpl.MSG_ON_SERVICE_STARTED) {
                latch.countDown();
                mService.stop();
                //mService.onDestroy();
            }
            if (action == LocationServiceImpl.MSG_ON_SERVICE_STOPPED) {
                latch.countDown();
                mService.onLocation(new BackgroundLocation());
            }
            if (action == LocationServiceImpl.MSG_ON_LOCATION) {
                latch.countDown();
            }
        }
    };

    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(InstrumentationRegistry.getTargetContext());
    lbm.registerReceiver(serviceBroadcastReceiver, new IntentFilter(LocationServiceImpl.ACTION_BROADCAST));

    Config config = Config.getDefault();
    config.setStartForeground(false);

    MockLocationProvider provider = new MockLocationProvider();
    Location location = new Location("gps");
    location.setProvider("mock");
    location.setElapsedRealtimeNanos(2000000000L);
    location.setAltitude(100);
    location.setLatitude(49);
    location.setLongitude(5);
    location.setAccuracy(105);
    location.setSpeed(50);
    location.setBearing(1);

    provider.setMockLocations(Arrays.asList(location));
    mLocationProviderFactory.setProvider(provider);

    mService.setLocationProviderFactory(mLocationProviderFactory);
    mService.configure(config);
    mService.start();

    latch.await();
    lbm.unregisterReceiver(serviceBroadcastReceiver);
}
 
Example 20
Source File: CbService.java    From PressureNet-SDK with MIT License 4 votes vote down vote up
private ArrayList<CbCurrentCondition> getCurrentConditionsFromLocalAPI(CbApiCall currentConditionAPI) {
	ArrayList<CbCurrentCondition> conditions = new ArrayList<CbCurrentCondition>();
	try {
		db.open();
		Cursor ccCursor = db.getCurrentConditions(
				currentConditionAPI.getMinLat(),
				currentConditionAPI.getMaxLat(),
				currentConditionAPI.getMinLon(),
				currentConditionAPI.getMaxLon(),
				currentConditionAPI.getStartTime(),
				currentConditionAPI.getEndTime(), 1000);

		while (ccCursor.moveToNext()) {
			CbCurrentCondition cur = new CbCurrentCondition();
			Location location = new Location("network");
			double latitude = ccCursor.getDouble(1);
			double longitude = ccCursor.getDouble(2);
			location.setLatitude(latitude);
			location.setLongitude(longitude);
			cur.setLat(latitude);
			cur.setLon(longitude);
			location.setAltitude(ccCursor.getDouble(3));
			location.setAccuracy(ccCursor.getInt(4));
			location.setProvider(ccCursor.getString(5));
			cur.setLocation(location);
			cur.setSharing_policy(ccCursor.getString(6));
			cur.setTime(ccCursor.getLong(7));
			cur.setTzoffset(ccCursor.getInt(8));
			cur.setUser_id(ccCursor.getString(9));
			cur.setGeneral_condition(ccCursor.getString(10));
			cur.setWindy(ccCursor.getString(11));
			cur.setFog_thickness(ccCursor.getString(12));
			cur.setCloud_type(ccCursor.getString(13));
			cur.setPrecipitation_type(ccCursor.getString(14));
			cur.setPrecipitation_amount(ccCursor.getDouble(15));
			cur.setPrecipitation_unit(ccCursor.getString(16));
			cur.setThunderstorm_intensity(ccCursor.getString(17));
			cur.setUser_comment(ccCursor.getString(18));
			conditions.add(cur);
		}
	} catch (Exception e) {
		log("cbservice get_current_conditions failed " + e.getMessage());
	} finally {
		db.close();
	}
	return conditions;
}