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

The following examples show how to use android.location.Location#setLongitude() . 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: CbScience.java    From PressureNet-SDK with MIT License 7 votes vote down vote up
public static double angle(double lat1, double long1, double lat2,
        double long2) {

	Location loc1 = new Location("network");
	loc1.setLatitude(lat1);
	loc1.setLongitude(long1);
	Location loc2 = new Location("network");
	loc2.setLatitude(lat2);
	loc2.setLongitude(long2);

    float brng = loc1.bearingTo(loc2);
    
    float readyForEnglish  = normalizeDegree(brng);
    
    log("cbscience bearingTo " + brng + ", eng " + readyForEnglish + " " + englishDirection(readyForEnglish));
    return readyForEnglish;
}
 
Example 2
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 3
Source File: AddEditApiaryPresenter.java    From go-bees with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
@Override
public void onApiaryLoaded(Apiary apiary) {
    this.apiary = apiary;
    // Show apiary data on view
    if (view.isActive()) {
        // Set name
        view.setName(apiary.getName());
        // Set notes
        view.setNotes(apiary.getNotes());
        // Set location
        if (apiary.hasLocation()) {
            Location apiaryLocation = new Location("");
            apiaryLocation.setLatitude(apiary.getLocationLat());
            apiaryLocation.setLongitude(apiary.getLocationLong());
            view.setLocation(apiaryLocation);
        }
    }
}
 
Example 4
Source File: SendMapsUtilsTest.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with a
 * title.
 */
public void testBuildMapsLineFeature_with_title() {
  ArrayList<Location> locations = new ArrayList<Location>();
  Location location = new Location("test");
  location.setLatitude(50.0);
  location.setLongitude(100.0);
  locations.add(location);
  MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature("name", locations);

  assertEquals(MapsFeature.LINE, mapFeature.getType());
  assertNotNull(mapFeature.getAndroidId());
  assertEquals("name", mapFeature.getTitle());
  assertEquals(0x80FF0000, mapFeature.getColor());
  assertEquals(50.0, mapFeature.getPoint(0).getLatitude());
  assertEquals(100.0, mapFeature.getPoint(0).getLongitude());
}
 
Example 5
Source File: GeofenceState.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public GeofenceState(Geofence fence, long expireAt,
        int allowedResolutionLevel, int uid, String packageName, PendingIntent intent) {
    mState = STATE_UNKNOWN;
    mDistanceToCenter = Double.MAX_VALUE;

    mFence = fence;
    mExpireAt = expireAt;
    mAllowedResolutionLevel = allowedResolutionLevel;
    mUid = uid;
    mPackageName = packageName;
    mIntent = intent;

    mLocation = new Location("");
    mLocation.setLatitude(fence.getLatitude());
    mLocation.setLongitude(fence.getLongitude());
}
 
Example 6
Source File: MapzenLocation.java    From open with GNU General Public License v3.0 6 votes vote down vote up
public static Location getDistancePointFromBearing(Location originalLocation,
        int distanceMeters, int bearing) {
    double orgLat = originalLocation.getLatitude();
    double orgLng = originalLocation.getLongitude();
    double dist = distanceMeters / KM / EARTH_RADIUS;
    double brng = Math.toRadians(bearing);
    double lat1 = Math.toRadians(orgLat);
    double lon1 = Math.toRadians(orgLng);

    double lat2 = Math.asin(
            Math.sin(lat1) * Math.cos(dist)
                    + Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
    double a = Math.atan2(
            Math.sin(brng) * Math.sin(dist) * Math.cos(lat1),
            Math.cos(dist) - Math.sin(lat1) * Math.sin(lat2));
    double lon2 = lon1 + a;

    lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI;

    Location location = new Location(LocationManager.GPS_PROVIDER);
    location.setLatitude(Math.toDegrees(lat2));
    location.setLongitude(Math.toDegrees(lon2));

    return location;
}
 
Example 7
Source File: Utils.java    From react-native-appmetrica with MIT License 5 votes vote down vote up
static Location toLocation(ReadableMap locationMap) {
    if (locationMap == null) {
        return null;
    }

    Location location = new Location("Custom");

    if (locationMap.hasKey("latitude")) {
        location.setLatitude(locationMap.getDouble("latitude"));
    }
    if (locationMap.hasKey("longitude")) {
        location.setLongitude(locationMap.getDouble("longitude"));
    }
    if (locationMap.hasKey("altitude")) {
        location.setAltitude(locationMap.getDouble("altitude"));
    }
    if (locationMap.hasKey("accuracy")) {
        location.setAccuracy((float) locationMap.getDouble("accuracy"));
    }
    if (locationMap.hasKey("course")) {
        location.setBearing((float) locationMap.getDouble("course"));
    }
    if (locationMap.hasKey("speed")) {
        location.setSpeed((float) locationMap.getDouble("speed"));
    }
    if (locationMap.hasKey("timestamp")) {
        location.setTime((long) locationMap.getDouble("timestamp"));
    }

    return location;
}
 
Example 8
Source File: CameraMetadataNative.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private Location getGpsLocation() {
    String processingMethod = get(CaptureResult.JPEG_GPS_PROCESSING_METHOD);
    double[] coords = get(CaptureResult.JPEG_GPS_COORDINATES);
    Long timeStamp = get(CaptureResult.JPEG_GPS_TIMESTAMP);

    if (areValuesAllNull(processingMethod, coords, timeStamp)) {
        return null;
    }

    Location l = new Location(translateProcessToLocationProvider(processingMethod));
    if (timeStamp != null) {
        // Location expects timestamp in [ms.]
        l.setTime(timeStamp * 1000);
    } else {
        Log.w(TAG, "getGpsLocation - No timestamp for GPS location.");
    }

    if (coords != null) {
        l.setLatitude(coords[0]);
        l.setLongitude(coords[1]);
        l.setAltitude(coords[2]);
    } else {
        Log.w(TAG, "getGpsLocation - No coordinates for GPS location");
    }

    return l;
}
 
Example 9
Source File: LiveTrackingTest.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
@SmallTest
public void testLiveTrackingGetMsgLiveShort() throws Exception {
    LiveTracking liveTracking = new LiveTracking(LiveTracking.TYPE_JAYPS, new Bus());
    Location location = new Location("JayPS");
    location.setAccuracy(5);
    location.setLatitude(48);
    location.setLongitude(3);
    location.setTime(1420980000000l);
    byte[] msgLiveShort = liveTracking.getMsgLiveShort(location);

    String[] names = liveTracking.getNames();
}
 
Example 10
Source File: Mapa.java    From android with GNU General Public License v2.0 5 votes vote down vote up
public void onClick(View v) {
	
	switch (v.getId()) {
	case R.id.btGuardarPosicion:
		// Guarda la posición actual en la Base de Datos
		Location location = mapa.getMyLocation();
           if (location != null) {
               Ubicacion ubicacion = new Ubicacion();
               ubicacion.setNombre("Desde Mapa");
               ubicacion.setPosicion(new LatLng(location.getLatitude(), location.getLongitude()));
               database.nuevaUbicacion(ubicacion);
           }
           else {
               Toast.makeText(this, R.string.sinubicacion_message, Toast.LENGTH_SHORT).show();
           }
		break;
	case R.id.btVerMiPosicion:
		// TODO
		break;
	case R.id.btDistancia:
		// Calcula la distancia en metros entre la posición actual y la última marca pulsada
		Location yo = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if ((marker != null) && (yo != null)) {
			Location loc = new Location(marker.getTitle());
			loc.setLatitude(marker.getPosition().latitude);
			loc.setLongitude(marker.getPosition().longitude);
			
			Toast.makeText(this, String.valueOf(yo.distanceTo(loc)), Toast.LENGTH_LONG).show();
		}
           else {
               Toast.makeText(this, R.string.distancia_error_message, Toast.LENGTH_LONG).show();
           }
		
		break;
	default:
		break;
	}
}
 
Example 11
Source File: LocationInfo.java    From Androzic with GNU General Public License v3.0 5 votes vote down vote up
private void updateLocationInfo(View view)
{

	Androzic application = Androzic.getApplication();

	Location loc = new Location("fake");
	loc.setLatitude(location[0]);
	loc.setLongitude(location[1]);

	((TextView) view.findViewById(R.id.coordinate_degree)).setText(StringFormatter.coordinates(0, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_degmin)).setText(StringFormatter.coordinates(1, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_degminsec)).setText(StringFormatter.coordinates(2, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_utmups)).setText(StringFormatter.coordinates(3, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_mgrs)).setText(StringFormatter.coordinates(4, " ", location[0], location[1]));

	Calendar now = GregorianCalendar.getInstance(TimeZone.getDefault());
	double sunrise = Astro.computeSunriseTime(application.getZenith(), loc, now);
	double sunset = Astro.computeSunsetTime(application.getZenith(), loc, now);

	if (Double.isNaN(sunrise))
	{
		((TextView) view.findViewById(R.id.sunrise)).setText(R.string.never);
	}
	else
	{
		((TextView) view.findViewById(R.id.sunrise)).setText(Astro.getLocalTimeAsString(sunrise));
	}
	if (Double.isNaN(sunset))
	{
		((TextView) view.findViewById(R.id.sunset)).setText(R.string.never);
	}
	else
	{
		((TextView) view.findViewById(R.id.sunset)).setText(Astro.getLocalTimeAsString(sunset));
	}
	double declination = application.getDeclination(location[0], location[1]);
	((TextView) view.findViewById(R.id.declination)).setText(String.format("%+.1f\u00B0", declination));
}
 
Example 12
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 13
Source File: GpxParser.java    From graphhopper-navigation-android with MIT License 5 votes vote down vote up
@NonNull
private Location buildGpxLocation(Double latitude, Double longitude, Long time) {
  Location gpxLocation = new Location(GPX_LOCATION_NAME);
  gpxLocation.setTime(time);
  gpxLocation.setLatitude(latitude);
  gpxLocation.setLongitude(longitude);
  return gpxLocation;
}
 
Example 14
Source File: RequestTests.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCreatePlacesSearchRequestWithLocation() {
    Location location = new Location("");
    location.setLatitude(47.6204);
    location.setLongitude(-122.3491);

    Request request = Request.newPlacesSearchRequest(null, location, 1000, 50, null, null);

    assertTrue(request != null);
    assertEquals(HttpMethod.GET, request.getHttpMethod());
    assertEquals("search", request.getGraphPath());
}
 
Example 15
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 16
Source File: SendFusionTablesUtilsTest.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)}
 * with no altitude.
 */
public void testAppendLocation_no_altitude() {
  StringBuilder builder = new StringBuilder();
  Location location = new Location("test");
  location.setLongitude(10.1);
  location.setLatitude(20.2);
  location.removeAltitude();
  SendFusionTablesUtils.appendLocation(location, builder);
  assertEquals("10.1,20.2", builder.toString());
}
 
Example 17
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
public static void getAltitude(long from, long to, Context context) throws IOException, JSONException {
    Log.i(TAG, "Get altitude" +
            " from=" + SimpleDateFormat.getDateTimeInstance().format(new Date(from)) +
            " to=" + SimpleDateFormat.getDateTimeInstance().format(new Date(to)));

    DatabaseHelper dh = null;
    Cursor cursor = null;
    boolean first = true;
    try {
        dh = new DatabaseHelper(context);
        cursor = dh.getLocations(from, to, true, true, true, 0);

        int colID = cursor.getColumnIndex("ID");
        int colTime = cursor.getColumnIndex("time");
        int colProvider = cursor.getColumnIndex("provider");
        int colLatitude = cursor.getColumnIndex("latitude");
        int colLongitude = cursor.getColumnIndex("longitude");
        int colAltitudeType = cursor.getColumnIndex("altitude_type");

        while (cursor.moveToNext()) {
            long id = cursor.getLong(colID);
            long time = cursor.getLong(colTime);
            final String provider = cursor.getString(colProvider);
            double latitude = cursor.getDouble(colLatitude);
            double longitude = cursor.getDouble(colLongitude);
            int altitude_type = (cursor.isNull(colAltitudeType) ? ALTITUDE_NONE : cursor.getInt(colAltitudeType));

            if ((altitude_type & ALTITUDE_KEEP) == 0 &&
                    (altitude_type & ~ALTITUDE_KEEP) != ALTITUDE_LOOKUP) {
                Location location = new Location(provider);
                location.setLatitude(latitude);
                location.setLongitude(longitude);
                location.setTime(time);
                GoogleElevationApi.getElevation(location, context);
                if (first)
                    first = false;
                else
                    try {
                        // Max. 5 requests/second
                        Thread.sleep(200);
                    } catch (InterruptedException ignored) {
                    }
                Log.i(TAG, "New altitude for location=" + location);
                dh.updateLocationAltitude(id, location.getAltitude(), ALTITUDE_LOOKUP);
            }
        }
    } finally {
        if (cursor != null)
            cursor.close();
        if (dh != null)
            dh.close();
    }
}
 
Example 18
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;
}
 
Example 19
Source File: AndroidLocationEngineImplTest.java    From mapbox-events-android with MIT License 4 votes vote down vote up
private static Location getMockLocation(double lat, double lon) {
  Location location = mock(Location.class);
  location.setLatitude(lat);
  location.setLongitude(lon);
  return location;
}
 
Example 20
Source File: RouteUtils.java    From graphhopper-navigation-android with MIT License 3 votes vote down vote up
/**
 * If navigation begins, a location update is sometimes needed to force a
 * progress change update as soon as navigation is started.
 * <p>
 * This method creates a location update from the first coordinate (origin) that created
 * the route.
 *
 * @param route with list of coordinates
 * @return {@link Location} from first coordinate
 * @since 0.10.0
 */
public Location createFirstLocationFromRoute(DirectionsRoute route) {
  List<Point> coordinates = route.routeOptions().coordinates();
  Point origin = coordinates.get(FIRST_COORDINATE);
  Location forcedLocation = new Location(FORCED_LOCATION);
  forcedLocation.setLatitude(origin.latitude());
  forcedLocation.setLongitude(origin.longitude());
  return forcedLocation;
}