简体   繁体   中英

Make setMyLocationEnabled only get location once

I use the following line to make sure that my map displays the current position of the device and a button that centers the camera on that location

mMap.setMyLocationEnabled(true);

Which is pretty standard stuff, however this means that the app keeps firing location requests draining battery. In my use case this is not needed, only checking the location once per onResume is enough.

I am however unable to find a solution for this. I can create a LocationRequest and make it only update once (see below) but this does not seem to apply to the setMyLocationEnabled function.

mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(15000)         // 15 seconds
            .setFastestInterval(16)    // 16ms = 60fps
            .setNumUpdates(1)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

I know I can set setMyLocationEnabled to false but this also removes the current location from the screen which I don't want.

So the way to do this was to implement LocationSource and use your own listener.

private OnLocationChangedListener mMapLocationListener;

When the map is setup call

mMap.setLocationSource(this);

Then use the GoogleApiclient and fused api to get the last location (and set the map camera to it)

Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LatLng currentPos = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLng(currentPos));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM