Java Code Examples for android.location.Location

The following are top voted examples for showing how to use android.location.Location. 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: BikeLine   File: NavigationActivity.java   Source Code and License 7 votes vote down vote up
@Override
public synchronized void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Start position marker
    mMap.addMarker(new MarkerOptions().
            position(startCoordinate).
            icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
    // end position marker
    mMap.addMarker(new MarkerOptions().
            position(endCoordinate).
            icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
    if(objectLocations!=null)
        for(com.nctu.bikeline.Model.Location objLocation:objectLocations){
            mMap.addMarker(new MarkerOptions().position(objLocation.getCoordinate())
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
        }
    // highlight route
    mMap.addPolyline(options);
    // move and zoom camera
    if(gpsService != null)
        updateDirectionOverlay(gpsService.getLocation(), 0, false);
}
 
Example 2
Project: coursera-sustainable-apps   File: LocLogServiceTest.java   Source Code and License 7 votes vote down vote up
private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)InstrumentationRegistry.getTargetContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {

        Location loc;

        try{
            loc = mLocationManager.getLastKnownLocation(provider);
        } catch (SecurityException e) {
            loc = null;
        }

        if (loc == null) {
            continue;
        }
        if (bestLocation == null || loc.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = loc;
        }
    }
    return bestLocation;
}
 
Example 3
Project: localcloud_fe   File: JSONHelper.java   Source Code and License 7 votes vote down vote up
/**
 * Converts location data into a JSON form that can be consumed within a JavaScript application
 * @param provider Indicates if this location is coming from gps or network provider
 * @param location The android Location
 * @param cached Indicates if the value was pulled from the device cache or not
 * @return Location data. Note: this library returns 0 rather than null to avoid nullPointExceptions
 */
public static String locationJSON(String provider, Location location, boolean cached) {

    final JSONObject json = new JSONObject();

    if(location != null){
        try {

            json.put("provider", provider);
            json.put("latitude", location.getLatitude());
            json.put("longitude", location.getLongitude());
            json.put("altitude", location.getAltitude());
            json.put("accuracy", location.getAccuracy());
            json.put("bearing", location.getBearing());
            json.put("speed", location.getSpeed());
            json.put("timestamp", location.getTime());
            json.put("cached", cached);
        }
        catch (JSONException exc) {
            logJSONException(exc);
        }
    }

    return json.toString();
}
 
Example 4
Project: home-assistant-Android   File: LocationUpdateReceiver.java   Source Code and License 7 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    prefs = Utils.getPrefs(context);
    switch (intent.getAction()) {
        case Intent.ACTION_BOOT_COMPLETED:
        case ACTION_START_LOCATION:
            apiClient = new GoogleApiClient.Builder(context)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

            apiClient.connect();
            break;
        case ACTION_LOCATION_UPDATE:
            if (prefs.getBoolean(Common.PREF_ENABLE_LOCATION_TRACKING, false) && LocationResult.hasResult(intent)) {
                LocationResult result = LocationResult.extractResult(intent);
                Location location = result.getLastLocation();
                if (location != null)
                    logLocation(location, context);
            }
            break;
    }
}
 
Example 5
Project: TransLinkMe-App   File: LocationFragment.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
private void getLastLocation() {
    mFusedLocationClient.getLastLocation()
            .addOnCompleteListener((Activity) getContext(), new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {

                    if (task.isSuccessful() && task.getResult() != null) {
                        mLastLocation = task.getResult();
                        Toast.makeText(getContext(), "Location set", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), "Location not set", Toast.LENGTH_SHORT).show();
                    }

                }
            });
}
 
Example 6
Project: mapbox-events-android   File: LocationReceiverTest.java   Source Code and License 6 votes vote down vote up
@Test
public void checksSendEventNotCalledWhenAltitudeNaN() throws Exception {
  Context mockedContext = mock(Context.class);
  Intent mockedIntent = mock(Intent.class);
  when(mockedIntent.getStringExtra(eq("location_received"))).thenReturn("onLocation");
  Bundle mockedBundle = mock(Bundle.class);
  when(mockedIntent.getExtras()).thenReturn(mockedBundle);
  Location mockedLocation = mock(Location.class);
  when(mockedBundle.get(eq(LocationManager.KEY_LOCATION_CHANGED))).thenReturn(mockedLocation);
  when(mockedLocation.getAltitude()).thenReturn(Double.NaN);
  EventSender mockedEventSender = mock(EventSender.class);
  LocationReceiver theLocationReceiver = new LocationReceiver(mockedEventSender);

  theLocationReceiver.onReceive(mockedContext, mockedIntent);

  verify(mockedEventSender, never()).send(any(LocationEvent.class));
}
 
Example 7
Project: ATMO972   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void findStationNearly() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        // Sur Défaut, l'on force la localisation de "FDF - Lycée Bellevue"
        stationMadininair= new StationsMadininair(14.602902, 61.077537);
        tvStationNearly.setText(R.string.find_station_error);
    } else
    {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //TODO: a controler si cela fonctionne avec d'autres périphériques
        Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        stationMadininair= new StationsMadininair(loc.getLatitude(), loc.getLongitude());
        tvStationNearly.setText(String.format("%s : %s",
                getString(R.string.display_station_nearly),
                Utilites.recupNomStation(stationMadininair.getNumStationNearly())));
    }
}
 
Example 8
Project: DejaVu   File: BackendService.java   Source Code and License 6 votes vote down vote up
/**
 * Check to see if the coverage area (location) of an RF emitter is close
 * enough to others in a group that we can believably add it to the group.
 * @param location The coverage area of the candidate emitter
 * @param locGroup The coverage areas of the emitters already in the group
 * @param radius The coverage radius expected for they type of emitter
 *                 we are dealing with.
 * @return
 */
private boolean locationCompatibleWithGroup(Location location,
                                            Set<Location> locGroup,
                                            double radius) {

    // If the location is within range of all current members of the
    // group, then we are compatible.
    for (Location other : locGroup) {
        double testDistance = (location.distanceTo(other) -
                location.getAccuracy() -
                other.getAccuracy());

        if (testDistance > radius) {
            return false;
        }
    }
    return true;
}
 
Example 9
Project: hypertrack-live-android   File: Home.java   Source Code and License 6 votes vote down vote up
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
    if (resultCode == FetchLocationIntentService.SUCCESS_RESULT) {
        LatLng latLng = resultData.getParcelable(FetchLocationIntentService.RESULT_DATA_KEY);
        if (latLng == null)
            return;
        defaultLocation.setLatitude(latLng.latitude);
        defaultLocation.setLongitude(latLng.longitude);
        Log.d(TAG, "Geocoding for Country Name Successful: " + latLng.toString());

        if (mMap != null) {
            if (defaultLocation.getLatitude() != 0.0 || defaultLocation.getLongitude() != 0.0)
                zoomLevel = 16.9f;

            // Check if any Location Data is available, meaning Country zoom level need not be used
            Location lastKnownCachedLocation = SharedPreferenceManager.getLastKnownLocation(Home.this);
            if (lastKnownCachedLocation != null && lastKnownCachedLocation.getLatitude() != 0.0
                    && lastKnownCachedLocation.getLongitude() != 0.0) {
                return;
            }

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
        }
    }
}
 
Example 10
Project: mocket_android_demo   File: MapsActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {

  //place marker at current position
  //mGoogleMap.clear();
  if (currLocationMarker != null) {
    currLocationMarker.remove();
  }
  latLng = new LatLng(location.getLatitude(), location.getLongitude());
  MarkerOptions markerOptions = new MarkerOptions();
  markerOptions.position(latLng);
  markerOptions.title(getString(R.string.current_position));
  markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
  currLocationMarker = mGoogleMap.addMarker(markerOptions);

  //zoom to current position:
  CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(latLng).zoom(14).build();

  mGoogleMap.animateCamera(CameraUpdateFactory
    .newCameraPosition(cameraPosition));

  mMocketClient.pushLatLngToServer(latLng);
}
 
Example 11
Project: MyFlightbookAndroid   File: MFBImageInfo.java   Source Code and License 6 votes vote down vote up
@Override
public void FromProperties(SoapObject so) {
    Comment = ReadNullableString(so, "Comment");
    VirtualPath = ReadNullableString(so, "VirtualPath");
    URLFullImage = ReadNullableString(so, "URLFullImage");
    ThumbnailFile = ReadNullableString(so, "ThumbnailFile");
    Width = Integer.parseInt(so.getProperty("Width").toString());
    Height = Integer.parseInt(so.getProperty("Height").toString());
    WidthThumbnail = Integer.parseInt(so.getProperty("WidthThumbnail").toString());
    HeightThumbnail = Integer.parseInt(so.getProperty("HeightThumbnail").toString());

    if (so.hasProperty("Location")) {
        SoapObject location = (SoapObject) so.getProperty("Location");
        Location = new LatLong();
        Location.FromProperties(location);
    }

    if (so.hasProperty("ImageType"))
        ImageType = ImageFileType.valueOf(so.getProperty("ImageType").toString());
}
 
Example 12
Project: Overkill   File: MapsActivity2.java   Source Code and License 6 votes vote down vote up
private void getCurPos () {
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        start = new LatLng(location.getLatitude(), location.getLongitude());
                        if (info == null)
                            info = getAddress(MapsActivity2.this, location.getLatitude(), location.getLongitude());
                        moveToPosition();
                    }
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(MapsActivity2.this, "Check Your GPS or network", Toast.LENGTH_SHORT).show();
                }
            });
}
 
Example 13
Project: Ships   File: ShowMapFragment.java   Source Code and License 6 votes vote down vote up
/**** START OwnLocationReceivedListener ****/

	@Override
	public void onOwnLocationReceived(final Location location) {
		logStatus("Own location received: Lon: " + GPS_COORD_FORMAT.format(location.getLongitude()) + ", Lat: " + GPS_COORD_FORMAT.format(location.getLatitude()));
		lastReceivedOwnLocation=location;

		if (getActivity()!=null){
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
                webView.loadUrl("javascript:setCurrentPosition(" + location.getLongitude() + "," + location.getLatitude() + ")");
				}
			});
		} else {
			Log.e(TAG,"Huh?");
		}
	}
 
Example 14
Project: Nibo   File: LocationRepository.java   Source Code and License 6 votes vote down vote up
public LocationRepository(Activity activity, GoogleApiClient mGoogleApiClient) {
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(activity);
    this.mGoogleApiClient = mGoogleApiClient;
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(activity, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        userLocation = location;
                        publishSubject.onNext(userLocation);

                        //addOverlay(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()));
                        //mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                    } else {
                        userLocation = null;
                    }
                }
            });
}
 
Example 15
Project: Remindy   File: PlaceActivity.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings({"MissingPermission"})
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String permissions[],
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_ACCESS_FINE_LOCATION_SHOW_ICON_IN_MAP:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setUpMap();
            }
            break;
        case PERMISSION_REQUEST_ACCESS_FINE_LOCATION_GET_LAST_LOCATION:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                if (lastLocation != null) {
                    moveCameraToLocation(lastLocation);
                }
            }
    }

}
 
Example 16
Project: Moodr   File: MapsActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;

    //remove previous current location Marker
    if (marker != null) {
        marker.remove();
    }

    current_Latitude = mLastLocation.getLatitude();
    current_Longitude = mLastLocation.getLongitude();
    marker = mMap.addMarker(new MarkerOptions().position(new LatLng(current_Latitude, current_Longitude))
            .title("My Location").icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(current_Latitude, current_Longitude), 8));

}
 
Example 17
Project: Camera-warner   File: MapsActivity.java   Source Code and License 6 votes vote down vote up
private void updateLocationOnMap(@NonNull Location location) {
    if (locationMarker != null) {
        locationMarker.remove();
    }

    LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
    if (!followed) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
        followed = true;
    }

    locationMarker = mMap.addMarker(new MarkerOptions().position(userLocation).title("Your location"));

    if (radiusCircle != null) {
        radiusCircle.remove();
    }
    radiusCircle = mMap.addCircle(new CircleOptions().center(locationMarker.getPosition()).radius(Double.parseDouble(PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.pref_radius_key), getString(R.string.pref_radius_default)))).fillColor(Color.argb(195, 102, 147, 173)));
}
 
Example 18
Project: cat-is-a-dog   File: AddHabitEventActivity.java   Source Code and License 6 votes vote down vote up
/**
 * Displays the habitEvent's details onto the edit page
 * @param habitEvent the habit event to be edited
 */
public void restoreHabitEvent(HabitEvent habitEvent) {
    editingHabitEventKey = habitEvent.getKey();
    habitKey = habitEvent.getHabitKey();

    if(habitEvent.getLatitude() !=0 && habitEvent.getLongitude() !=0) {
        location = new Location("");
        location.setLatitude(habitEvent.getLatitude());
        location.setLongitude(habitEvent.getLongitude());

        //map updated in onMapReady()
    }

    if(habitEvent.getPhotoUrl() != null) {
        byte[] decodedByteArray = Base64.decode(habitEvent.getPhotoUrl(), Base64.NO_WRAP);
        imageBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedByteArray.length);
        image.setImageBitmap(imageBitmap);
    }

    if(habitEvent.getComment() != null && !Objects.equals(habitEvent.getComment(), "")) {
        comment.setText(habitEvent.getComment());
    }

    creationDate.setText("Created: "+ habitEvent.getEventDate().toString("EEEE MMMM d, YYYY"));
}
 
Example 19
Project: Leanplum-Android-SDK   File: LocationManagerImplementation.java   Source Code and License 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
  if (!location.hasAccuracy()) {
    Log.e("Received a location with no accuracy.");
    return;
  }

  // Currently, location segment treats GPS and CELL the same. In the future, we might want more
  // distinction in the accuracy types. For example, a customer might want to send messages only
  // to the ones with very accurate location information. We are assuming that it is from GPS if
  // the location accuracy is less than or equal to |ACCURACY_THRESHOLD_GPS|.
  LeanplumLocationAccuracyType locationAccuracyType =
      location.getAccuracy() >= ACCURACY_THRESHOLD_GPS ?
          LeanplumLocationAccuracyType.CELL : LeanplumLocationAccuracyType.GPS;

  if (!isSendingLocation && needToSendLocation(locationAccuracyType)) {
    try {
      setUserAttributesForLocationUpdate(location, locationAccuracyType);
    } catch (Throwable t) {
      Util.handleException(t);
    }
  }

  LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
 
Example 20
Project: IM_Here   File: UserDataFirebase.java   Source Code and License 5 votes vote down vote up
/**
 * Set User Location
 */
public void updateUserLocation(Location location){
    CurrentLocation currentLocation =
            new CurrentLocation(location.getLongitude(),location.getLatitude()," ");

    FirebaseHelper.getUserLocation(USER_LINK_FIREBASE)
            .setValue(currentLocation);
}
 
Example 21
Project: boohee_v5.6   File: UMLocation.java   Source Code and License 5 votes vote down vote up
public static UMLocation build(Location location) {
    try {
        if (!(location.getLatitude() == 0.0d || location.getLongitude() == 0.0d)) {
            return new UMLocation(location.getLatitude(), location.getLongitude());
        }
    } catch (Exception e) {
    }
    return null;
}
 
Example 22
Project: Leanplum-Android-SDK   File: LeanplumLocationManagerTest.java   Source Code and License 5 votes vote down vote up
/**
 * A helper method for testing setUserAttributesForLocationUpdate.
 *
 * @param location User location.
 * @param locationAccuracyType Accuracy of the user location.
 * @param latLonExpected Expected string of latitude of longitude to be sent.
 * @throws Exception
 */
private void verifySetUserAttributesForLocationUpdate(Location location,
    final LeanplumLocationAccuracyType locationAccuracyType, final String latLonExpected) throws
    Exception {
  RequestHelper.addRequestHandler(new RequestHelper.RequestHandler() {
    @Override
    public void onRequest(String httpMethod, String apiMethod, Map<String, Object> params) {
      assertEquals(Constants.Methods.SET_USER_ATTRIBUTES, apiMethod);
      assertEquals(latLonExpected, params.get("location"));
      assertEquals(locationAccuracyType, params.get("locationAccuracyType"));
    }
  });
  Leanplum.setDeviceLocation(location);
}
 
Example 23
Project: SpaceRace   File: MapActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a callback for receiving location events.
 */
private void createLocationCallback() {
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(final LocationResult locationResult) {
            super.onLocationResult(locationResult);

            if (mRequestingLocationUpdates) {

                Log.i(TAG, "update event");
                Location oldLocation = mCurrentLocation;

                mCurrentLocation = locationResult.getLastLocation();

                if (initialPosition == null) {
                    initialPosition = mCurrentLocation;

                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(initialPosition.getLatitude(),
                                    initialPosition.getLongitude()), DEFAULT_ZOOM));

                    Log.d("INITIAL_POSITION", initialPosition.getLatitude() + " " +
                            initialPosition.getLongitude());

                    createAndDrawPath();
                }

                mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
                updateUI(oldLocation);
            }

        }
    };
}
 
Example 24
Project: DoorAccess   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void updateLocation(Location location) {
    Log.i(TAG, "updateLocation");

    /* maybe save the location for create location-tag relationship */
    mLocation = location;
}
 
Example 25
Project: mapbox-events-android   File: LocationReceiverInstrumentationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checksLocationIntent() throws Exception {
  LocationReceiver theLocationReceiver = new LocationReceiver();
  Intent expectedLocationIntent = new Intent("com.mapbox.location_receiver");
  expectedLocationIntent.putExtra("location_received", "onLocation");
  Location mockedLocation = mock(Location.class);

  Intent locationIntent = theLocationReceiver.supplyIntent(mockedLocation);

  assertTrue(locationIntent.filterEquals(expectedLocationIntent));
  assertTrue(locationIntent.hasExtra("location_received"));
  assertTrue(locationIntent.getStringExtra("location_received").equals("onLocation"));
  assertTrue(locationIntent.hasExtra(LocationManager.KEY_LOCATION_CHANGED));
  assertEquals(mockedLocation, locationIntent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED));
}
 
Example 26
Project: thingplug-sdk-android   File: SensorListener.java   Source Code and License 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    float latitude = (float) location.getLatitude();
    float longitude = (float) location.getLongitude();
    float altitude = (float) location.getAltitude();

    for (SensorInfo sensorInfo : sensorInfos) {
        if (sensorInfo.getType() == SensorType.GPS) {
            sensorInfo.setValues(new float[]{latitude, longitude, altitude});
            break;
        }
    }
}
 
Example 27
Project: CustomAndroidOneSheeld   File: GpsShield.java   Source Code and License 5 votes vote down vote up
@Override
public void sendFrameHandler(Location location) {
    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        if (eventHandler != null) {
            eventHandler.onLangChanged(latitude + "");
            eventHandler.onLatChanged(longitude + "");
        }
        sendFrame(location);
    }
}
 
Example 28
Project: LocationAware   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override public void onLocationChanged(Location location) {
  mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
      new LatLng(location.getLatitude(), location.getLongitude()), 15), 10,
      new GoogleMap.CancelableCallback() {
        @Override public void onFinish() {

        }

        @Override public void onCancel() {

        }
      });
}
 
Example 29
Project: Phoenicia   File: LocationField.java   Source Code and License 5 votes vote down vote up
@Override
public void set(Cursor c, String fieldName) {
	double lat = c.getDouble(c.getColumnIndexOrThrow(latName(fieldName)));
	double lng = c.getDouble(c.getColumnIndexOrThrow(lngName(fieldName)));
	
	Location l = new Location(LocationManager.GPS_PROVIDER);
	l.setLatitude(lat);
	l.setLongitude(lng);
	
	mValue = l;
}
 
Example 30
Project: Farmacias   File: MapTabPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public String onGetAddressFromLocation(Location currentLocation) {


    List<Address> addresses = null;
    try {
        addresses = mGeocoder.getFromLocation(
                currentLocation.getLatitude(),
                currentLocation.getLongitude(),
                1);
    } catch (IOException ioe) {

    }

    if (addresses == null || addresses.size() == 0) {
        Utils.logD(LOG_TAG, "no address found");
        return null;
    } else {
        Address address = addresses.get(0);
        StringBuilder stringBuilder = new StringBuilder();

        // Fetch the address lines using getAddressLine,
        // join them, and send them to the thread.
        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            if (i == 0) {
                preferencesManager.saveStreet(address.getAddressLine(i));
            }
            stringBuilder.append(address.getAddressLine(i));
            if (i != address.getMaxAddressLineIndex() - 1) {
                stringBuilder.append(Constants.COMMA);
            }
        }
        Utils.logD(LOG_TAG, "address found");
        mAddress = stringBuilder.toString();
        return mAddress;
    }


}
 
Example 31
Project: dagger-test-example   File: TomorrowWeatherViewModel.java   Source Code and License 5 votes vote down vote up
public void loadForecastWeatherDataForTomorrow()
{
    Location lastKnownLocation = locationService.lastLocation();
    if (lastKnownLocation != null)
    {
        double longitude = lastKnownLocation.getLongitude();
        double latitude = lastKnownLocation.getLatitude();
        dispatchRequestStarted();
        weatherService.getForecastWeather(longitude, latitude)
                .map(weatherParser::parse)
                .observeOn(androidScheduler)
                .subscribe(this::handleForecastDataResult, this::showError);
    }
}
 
Example 32
Project: civify-app   File: LocationAdapter.java   Source Code and License 5 votes vote down vote up
private void handleNewLocation(@NonNull Location location) {
    Log.d(TAG, "Location received: " + location);
    if (isLocationPlausible(location)) {
        Location previous = mLastLocation;
        mLastLocation = location;
        if (previous == null && hasPermissions()) mOnPermissionsChangedListeners.run();
        cancelLocationUpdateTimeout();
        executeUpdateLocationListener();
        rescheduleLocationUpdateTimeout();
    } else Log.d(TAG, "Location discarded.");
    if (!isAutoRefresh()) setAutoRefresh(false);
}
 
Example 33
Project: mapbox-events-android   File: LocationReceiver.java   Source Code and License 5 votes vote down vote up
private boolean sendEvent(Location location, Context context) {
  if (isThereAnyNaN(location) || isThereAnyInfinite(location)) {
    return false;
  }

  EventSender eventSender = obtainEventSender(context);
  LocationMapper obtainLocationEvent = obtainLocationMapper();
  LocationEvent locationEvent = obtainLocationEvent.from(location);
  eventSender.send(locationEvent);
  return true;
}
 
Example 34
Project: mapbox-navigation-android   File: NavigationHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Takes in a raw location, converts it to a point, and snaps it to the closest point along the
 * route. This is isolated as separate logic from the snap logic provided because we will always
 * need to snap to the route in order to get the most accurate information.
 */
static Point userSnappedToRoutePosition(Location location, List<Point> coordinates) {
  if (coordinates.size() < 2) {
    return Point.fromLngLat(location.getLongitude(), location.getLatitude());
  }

  Point locationToPoint = Point.fromLngLat(location.getLongitude(), location.getLatitude());

  // Uses Turf's pointOnLine, which takes a Point and a LineString to calculate the closest
  // Point on the LineString.
  Feature feature = TurfMisc.pointOnLine(locationToPoint, coordinates);
  return ((Point) feature.geometry());
}
 
Example 35
Project: FiveMinsMore   File: TrackingService.java   Source Code and License 5 votes vote down vote up
@WorkerThread
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    count++;
    if (LocationResult.hasResult(intent)) {
        // 從fusedLocationApi取得位置資料
        LocationResult locationResult = LocationResult.extractResult(intent);
        Location location = locationResult.getLastLocation();
        if (location != null) {
            succeed++;

            // 若小於最小間距,則不紀錄該航跡
            if (mTrkpts.size() > 1) {
                double interval = SphericalUtil.computeDistanceBetween(
                        new LatLng(location.getLatitude(), location.getLongitude()),
                        new LatLng(mLastPosition.getLatitude(), mLastPosition.getLongitude()));
                if (interval < DISTANCE_INTERVAL_FOR_TRKPTS)
                    return START_STICKY;
            }

            mTrkpts.add(location);
            mLastPosition = location;

            // Send Location Update to Activity
            if (callBack != null)
                callBack.getServiceData(location);
        }
    }

    // Message for testing
    Log.d(TAG, "Record Times: " + count + ", Succeed times: " + succeed +
            ",  Points number: " + mTrkpts.size()
            + ", Time from start: " + (new Date().getTime() - startTime) / 1000);

    return START_STICKY;
}
 
Example 36
Project: oma-riista-android   File: EntryMapView.java   Source Code and License 5 votes vote down vote up
public void moveCameraTo(Location location) {
    if (mMap == null) {
        // Map not yet ready, store location for later
        mUpdatedLocation = location;
        return;
    }

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), MAP_ZOOM_LEVEL_DEFAULT));
}
 
Example 37
Project: flutter_geolocation   File: GpsCoordinatesPlugin.java   Source Code and License 5 votes vote down vote up
private void returnLocation(Location location) {
  HashMap<String, Double> coordinates = new HashMap<>();
  coordinates.put("lat", location.getLatitude());
  coordinates.put("long", location.getLongitude());
  _client.disconnect();
  _result.success(coordinates);
}
 
Example 38
Project: Sega   File: ProductSoldFragmentProfile.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (LocationResult.hasResult(intent)) {
        LocationResult locationResult = LocationResult.extractResult(intent);
        Location location = locationResult.getLastLocation();
        if (location != null) {
            GPSTracker.mLastestLocation = new LatLng(location.getLatitude(), location.getLongitude());
            adapter.notifyDataSetChanged();
        }
    }
}
 
Example 39
Project: Nibo   File: BaseNiboFragment.java   Source Code and License 5 votes vote down vote up
protected void initmap() {
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mLocationRepository = new LocationRepository(getActivity(), mGoogleApiClient);

    mLocationRepository.getLocationObservable()
            .subscribe(new Consumer<Location>() {
                @Override
                public void accept(@NonNull Location location) throws Exception {
                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(location.getLatitude(), location.getLongitude()))
                            .zoom(15)
                            .build();
                    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                    handleLocationRetrieval(location);
                    extractGeocode(location.getLatitude(), location.getLongitude());

                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) throws Exception {
                    throwable.printStackTrace();
                }
            });


}
 
Example 40
Project: chat-sdk-android-push-firebase   File: PlacePickerFragment.java   Source Code and License 5 votes vote down vote up
private Request createRequest(Location location, int radiusInMeters, int resultsLimit, String searchText,
        Set<String> extraFields,
        Session session) {
    Request request = Request.newPlacesSearchRequest(session, location, radiusInMeters, resultsLimit, searchText,
            null);

    Set<String> fields = new HashSet<String>(extraFields);
    String[] requiredFields = new String[]{
            ID,
            NAME,
            LOCATION,
            CATEGORY,
            WERE_HERE_COUNT
    };
    fields.addAll(Arrays.asList(requiredFields));

    String pictureField = adapter.getPictureFieldSpecifier();
    if (pictureField != null) {
        fields.add(pictureField);
    }

    Bundle parameters = request.getParameters();
    parameters.putString("fields", TextUtils.join(",", fields));
    request.setParameters(parameters);

    return request;
}
 
Example 41
Project: VennTracker   File: Circles.java   Source Code and License 5 votes vote down vote up
private static ArrayList<LatLng> simplifyIntersections(ArrayList<LatLng> intersections) {
    // If the size is 1, no need to check anything
    if (intersections.size() > 1) {
        // Loop from the end so we can remove a without an error
        for (int a = intersections.size() - 1; a > 0; a--) {
            for (int b = 0; b < intersections.size(); b++) {
                // don't check itself
                if (a == b) {
                    continue;
                }
                // Get the distance between the 2 points
                float[] distanceIntersections = new float[2];
                Location.distanceBetween(
                        intersections.get(a).latitude,
                        intersections.get(a).longitude,
                        intersections.get(b).latitude,
                        intersections.get(b).longitude,
                        distanceIntersections);
                // Our margin of error is 20 meters
                //This isn't perfect but it will get us a close enough solution
                if (distanceIntersections[0] < 20) {
                    // Too close, remove it
                    intersections.remove(a);
                    if (intersections.size() > 1) {
                        // Recursivly remove locations
                        return simplifyIntersections(intersections);
                    }
                }
            }
        }
    }
    return intersections;
}
 
Example 42
Project: piast-trail   File: PlaceDetailsActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.place_details);
    mContext = this;
    mResources = getResources();
    
    mMapFragment = (SupportMapFragment)
            getSupportFragmentManager().findFragmentById(R.id.place_map);
    
    mMapFragment.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap map) {
            mMap = map;
            updateUI();
        }
    });
    
    mPlaceId = getIntent().getIntExtra(EXTRA_PLACE_POSITION, -1);
    final VisitableGenerator generator = VisitableGenerator.get(this);
    mPlace = generator.getPlace(mPlaceId);
    mLocation = new Location("");
    mLocation.set(mPlace.getLocation());
    
    mPlaceImageViewFull = (ImageView) findViewById(R.id.place_image_full);
    mPlaceCaption = (TextView) findViewById(R.id.place_caption_full);
    mWebView = (WebView) findViewById(R.id.web_view);
    mBackupEmptyView = (TextView) findViewById(R.id.place_backup_empty_view);
    mIndicator = (ProgressBar) findViewById(R.id.indicator);
    mVisitedCheckBox = (CheckBox) findViewById(R.id.visited_check_box);
    
    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    mProgressBar.setMax(100);
    
    mWebView.setWebChromeClient(new WebChromeClient() {
        
        @Override
        public void onProgressChanged(WebView webView, int newProgress) {
            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);
            } else {
                mProgressBar.setVisibility(View.VISIBLE);
                mProgressBar.setProgress(newProgress);
            }
        }
    });
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.loadUrl(mPlace.getWikiUrl());
    
    Bitmap bitmap = PictureUtils.decodeBitmapFromResource(getResources(),
            mPlace.getImgResourceId(), 400, 400);
    
    mPlaceImageViewFull.setImageBitmap(bitmap);
    mPlaceCaption.setText(mPlace.getPlaceNameResId());
    this.getSupportActionBar().setTitle(mPlace.getPlaceNameResId());
    
    mVisitedCheckBox.setChecked(mPlace.isVisited());
    mVisitedCheckBox.setOnCheckedChangeListener(
            new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton view, boolean isChecked) {
            mPlace.setVisited(isChecked);
        }
    });
    
    mConnManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    
    NetworkInfo activeNetwork = mConnManager.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnected();
    
    if (!isConnected) {
        mIndicator.setVisibility(View.INVISIBLE);
        mBackupEmptyView.setText(R.string.empty_placeholder);
    }
}
 
Example 43
Project: Android-Wear-Projects   File: MapsActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onConnected(@Nullable Bundle bundle) {

    if (checkPermission()) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
    }else{

    }

}
 
Example 44
Project: mapbox-navigation-android   File: NavigationTelemetry.java   Source Code and License 5 votes vote down vote up
@Override
public void onArrival(Location location, RouteProgress routeProgress) {
  // Update arrival time stamp
  navigationSessionState = navigationSessionState.toBuilder().arrivalTimestamp(new Date()).build();
  updateLifecyclePercentages();
  // Send arrival event
  NavigationMetricsWrapper.arriveEvent(navigationSessionState, routeProgress, metricLocation.getLocation());

  // Reset the departure listener if there is another leg in the route
  if (!RouteUtils.isLastLeg(routeProgress)) {
    resetArrivalListener();
  }
}
 
Example 45
Project: oma-riista-android   File: GameHarvest.java   Source Code and License 5 votes vote down vote up
public static GameHarvest createNew() {
    GameHarvest harvest = new GameHarvest(-1, 1, null, Calendar.getInstance(), TYPE_HARVEST, null, new ArrayList<LogImage>());
    harvest.mClientDataFormat = AppConfig.HARVEST_SPEC_VERSION;
    harvest.mLocation = new Location("");
    harvest.mType = TYPE_HARVEST;
    harvest.mCanEdit = true;
    harvest.mSent = false;
    harvest.mMobileClientRefId = GameDatabase.generateMobileRefId(new Random());

    return harvest;
}
 
Example 46
Project: letv   File: e.java   Source Code and License 5 votes vote down vote up
public b(e eVar, Location location, int i, int i2, int i3, long j) {
    if (location != null) {
        this.a = new Location(location);
        this.c = i2;
        this.b = j;
    }
}
 
Example 47
Project: MyFlightbookAndroid   File: LocSample.java   Source Code and License 5 votes vote down vote up
LocSample(Location l) {
    super();
    Latitude = l.getLatitude();
    Longitude = l.getLongitude();
    Alt = (int) (l.getAltitude() * MFBConstants.METERS_TO_FEET);
    Speed = l.getSpeed() * MFBConstants.MPS_TO_KNOTS;
    HError = l.getAccuracy();
    TimeStamp.setTime(l.getTime());
    TZOffset = 0;
}
 
Example 48
Project: Camera-warner   File: DataProviderManager.java   Source Code and License 5 votes vote down vote up
/**
 * Checks if a camera is nearer than radius to referenceLocation
 * @param radius The radius in which a camera will trigger around referenceLocation
 * @param referenceLocation The Location which is used as reference to check for Cameras
 * @return Whether a camera is in the radius radius of the Location referenceLocation
 */
public boolean isCameraNearerThan(float radius, Location referenceLocation)
{
    for (DataProvider provider : getDataProviders()) {
        if (provider.hasData()) {
            if (provider.distanceToNearestCamera(referenceLocation) < radius) {
                return true;
            }
        }
    }
    return false;
}
 
Example 49
Project: mapbox-events-android   File: LocationMapperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checksLocationEventWithAccuracyMapping() throws Exception {
  Location mockedLocation = mock(Location.class);
  when(mockedLocation.hasAccuracy()).thenReturn(true);
  when(mockedLocation.getAccuracy()).thenReturn(1.9f);
  LocationMapper obtainLocationEvent = new LocationMapper();

  LocationEvent actualLocationEvent = obtainLocationEvent.from(mockedLocation);

  assertEquals(2.0, actualLocationEvent.getAccuracy(), 0);
}
 
Example 50
Project: labtablet   File: AsyncWeatherFetcher.java   Source Code and License 5 votes vote down vote up
@Override
protected Integer doInBackground(Context... params) {

    HttpResponse response;
    try {
        LocationManager lm = (LocationManager) params[0].getSystemService(Context.LOCATION_SERVICE);
        Criteria crit = new Criteria();
        crit.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(crit, true);

        Location loc = lm.getLastKnownLocation(provider);

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();

        request.setURI(new URI(Utils.WEATHER_URL + "lat=" +
                loc.getLatitude() +
                "&lon=" +
                +loc.getLongitude()
                + "&units=metric"));

        response = client.execute(request);
        String result = EntityUtils.toString(response.getEntity());
        JSONObject jsonResponse = new JSONObject(result);
        JSONObject jsonWeather = jsonResponse.getJSONObject("main");
        return jsonWeather.getInt("temp");

    } catch (Exception e) {
        error = e;
    }
    return 0;
}
 
Example 51
Project: CustomAndroidOneSheeld   File: GpsShield.java   Source Code and License 5 votes vote down vote up
private void sendFrame(Location myLocation) {
    // TODO Auto-generated method stub
    frame = new ShieldFrame(UIShield.GPS_SHIELD.getId(), GPS_VALUE);
    float lat = (float) myLocation.getLatitude();
    float lang = (float) myLocation.getLongitude();
    frame.addArgument(lat);
    frame.addArgument(lang);
    sendShieldFrame(frame);

}
 
Example 52
Project: mapbox-navigation-hud-demo   File: GeocodeActivity.java   Source Code and License 5 votes vote down vote up
private void launchDisplay(Place place) {
  Intent displayActivity = new Intent(this, DisplayActivity.class);
  Location placeLocation = new Location(TAG);
  placeLocation.setLatitude(place.getLatLng().latitude);
  placeLocation.setLongitude(place.getLatLng().longitude);
  displayActivity.putExtra(PLACE_LOCATION_EXTRA, placeLocation);
  startActivity(displayActivity);
}
 
Example 53
Project: Expert-Android-Programming   File: SelectDeliveryAreaActivity.java   Source Code and License 5 votes vote down vote up
private void handleLocation(Location location) {
    if (location != null) {
        MyLg.e(TAG, "getLatitude() = " + String.valueOf(location.getLatitude()) + "\n getLongitude() = " + String.valueOf(location.getLongitude()));
        stopListener();

        getNearbyLocation(location);

    }
}
 
Example 54
Project: mapbox-navigation-android   File: RerouteActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
  if (tracking) {
    locationLayerPlugin.forceLocationUpdate(location);
    CameraPosition cameraPosition = new CameraPosition.Builder()
      .zoom(15)
      .target(new LatLng(location.getLatitude(), location.getLongitude()))
      .bearing(location.getBearing())
      .build();
    mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 2000);
  }
}
 
Example 55
Project: share-location   File: GPSHelper.java   Source Code and License 5 votes vote down vote up
public void locationPusher(Location currentLocation) {
    if (currentLocation != null) {
        double lat = currentLocation.getLatitude();
        double lon = currentLocation.getLongitude();

        Double[] data = new Double[]{lat, lon};

        if (FirebaseAuth.getInstance().getCurrentUser() != null) {
            String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
            FirebaseHelper.pushToFirebaseOnLocationUpdate(userId, data);
        }

    }
}
 
Example 56
Project: GeoFencer   File: GeoLocationProvider.java   Source Code and License 5 votes vote down vote up
private Location getLastKnowLocation() {
    if (googleApiClient.isConnected() &&
        ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        return LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    }
    return null;
}
 
Example 57
Project: mapbox-navigation-android   File: OffRouteDetector.java   Source Code and License 5 votes vote down vote up
/**
 * Method to check if the user has passed either the set (in {@link MapboxNavigationOptions})
 * minimum amount of seconds or minimum amount of meters since the last reroute.
 * <p>
 * If the user is above both thresholds, then the off-route can proceed.  Otherwise, ignore.
 *
 * @param location current location from engine
 * @param options  for second (default 3) / distance (default 50m) minimums
 * @return true if valid, false if not
 */
private boolean validOffRoute(Location location, MapboxNavigationOptions options) {
  // Check if minimum amount of distance has been passed since last reroute
  Point currentPoint = Point.fromLngLat(location.getLongitude(), location.getLatitude());
  double distanceFromLastReroute = 0d;
  if (lastReroutePoint != null) {
    distanceFromLastReroute = TurfMeasurement.distance(lastReroutePoint,
      currentPoint, TurfConstants.UNIT_METERS);
  } else {
    // If null, this is our first update - set the last reroute point to the given location
    updateLastReroutePoint(location);
  }
  return distanceFromLastReroute > options.minimumDistanceBeforeRerouting();
}
 
Example 58
Project: mapbox-navigation-android   File: OffRouteDetector.java   Source Code and License 5 votes vote down vote up
/**
 * uses dead reckoning to find the users future location.
 *
 * @return a {@link Point}
 * @since 0.2.0
 */
private static Point getFuturePosition(Location location, MapboxNavigationOptions options) {
  // Find future location of user
  Point locationToPosition = Point.fromLngLat(location.getLongitude(), location.getLatitude());
  double metersInFrontOfUser = location.getSpeed() * options.deadReckoningTimeInterval();
  return TurfMeasurement.destination(
    locationToPosition, metersInFrontOfUser, location.getBearing(), TurfConstants.UNIT_METERS
  );
}
 
Example 59
Project: Camera-warner   File: OSMDataProvider.java   Source Code and License 5 votes vote down vote up
@Override
public Set<Camera> loadData(Location newLocation) {
    if(newLocation==null)
    {
        Log.d("OSMDataProvider", "location is null. ignoring");
        return new LinkedHashSet<>();
    }

    Log.d("OSMDataProvider", String.format("Fetching data for Latitude=%f, Longitude=%f", newLocation.getLatitude(), newLocation.getLongitude()));
    return fetchForLocation(newLocation);
}
 
Example 60
Project: mapbox-navigation-android   File: NavigationService.java   Source Code and License 5 votes vote down vote up
/**
 * Runs several checks on the actual rawLocation object itself in order to ensure that we are
 * performing navigation progress on a accurate/valid rawLocation update.
 */
@SuppressWarnings("MissingPermission")
private boolean validLocationUpdate(Location location) {
  if (locationEngine.getLastLocation() == null) {
    return true;
  }
  // If the locations the same as previous, no need to recalculate things
  return !(location.equals(locationEngine.getLastLocation())
    || (location.getSpeed() <= 0 && location.hasSpeed())
    || location.getAccuracy() >= 100);
}