Java 类android.location.Location 实例源码

项目:BikeLine    文件:NavigationActivity.java   
@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);
}
项目:coursera-sustainable-apps    文件:LocLogServiceTest.java   
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;
}
项目:home-assistant-Android    文件:LocationUpdateReceiver.java   
@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;
    }
}
项目:TransLinkMe-App    文件:LocationFragment.java   
@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();
                    }

                }
            });
}
项目:mapbox-events-android    文件:LocationReceiverTest.java   
@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));
}
项目:ATMO972    文件:MainActivity.java   
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())));
    }
}
项目:DejaVu    文件:BackendService.java   
/**
 * 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;
}
项目:hypertrack-live-android    文件:Home.java   
@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));
        }
    }
}
项目:mocket_android_demo    文件:MapsActivity.java   
@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);
}
项目:MyFlightbookAndroid    文件:MFBImageInfo.java   
@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());
}
项目:Overkill    文件:MapsActivity2.java   
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();
                }
            });
}
项目:Ships    文件:ShowMapFragment.java   
/**** 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?");
        }
    }
项目:Nibo    文件:LocationRepository.java   
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;
                    }
                }
            });
}
项目:Remindy    文件:PlaceActivity.java   
@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);
                }
            }
    }

}
项目:Moodr    文件:MapsActivity.java   
@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));

}
项目:Camera-warner    文件:MapsActivity.java   
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)));
}
项目:localcloud_fe    文件:JSONHelper.java   
/**
 * 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();
}
项目:cat-is-a-dog    文件:AddHabitEventActivity.java   
/**
 * 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"));
}
项目:Leanplum-Android-SDK    文件:LocationManagerImplementation.java   
@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);
}
项目:IM_Here    文件:UserDataFirebase.java   
/**
 * Set User Location
 */
public void updateUserLocation(Location location){
    CurrentLocation currentLocation =
            new CurrentLocation(location.getLongitude(),location.getLatitude()," ");

    FirebaseHelper.getUserLocation(USER_LINK_FIREBASE)
            .setValue(currentLocation);
}
项目:boohee_v5.6    文件:UMLocation.java   
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;
}
项目:Leanplum-Android-SDK    文件:LeanplumLocationManagerTest.java   
/**
 * 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);
}
项目:SpaceRace    文件:MapActivity.java   
/**
 * 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);
            }

        }
    };
}
项目:DoorAccess    文件:MainActivity.java   
@Override
public void updateLocation(Location location) {
    Log.i(TAG, "updateLocation");

    /* maybe save the location for create location-tag relationship */
    mLocation = location;
}
项目:mapbox-events-android    文件:LocationReceiverInstrumentationTest.java   
@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));
}
项目:thingplug-sdk-android    文件:SensorListener.java   
@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;
        }
    }
}
项目:CustomAndroidOneSheeld    文件:GpsShield.java   
@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);
    }
}
项目:LocationAware    文件:MainActivity.java   
@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() {

        }
      });
}
项目:Phoenicia    文件:LocationField.java   
@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;
}
项目:Farmacias    文件:MapTabPresenter.java   
@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;
    }


}
项目:dagger-test-example    文件:TomorrowWeatherViewModel.java   
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);
    }
}
项目:civify-app    文件:LocationAdapter.java   
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);
}
项目:mapbox-events-android    文件:LocationReceiver.java   
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;
}
项目:mapbox-navigation-android    文件:NavigationHelper.java   
/**
 * 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());
}
项目:FiveMinsMore    文件:TrackingService.java   
@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;
}
项目:oma-riista-android    文件:EntryMapView.java   
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));
}
项目:flutter_geolocation    文件:GpsCoordinatesPlugin.java   
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);
}
项目:Sega    文件:ProductSoldFragmentProfile.java   
@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();
        }
    }
}
项目:Nibo    文件:BaseNiboFragment.java   
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();
                }
            });


}
项目:chat-sdk-android-push-firebase    文件:PlacePickerFragment.java   
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;
}