Reputation: 47
I have a question about working with the built-in "my location"-button. In my setup I have
mMap.setMyLocationEnabled(true);
So, the button is rendered on the map and when the GPS is turned on, it works like a charm. When GPS is turned off, it doesn't work anymore. Is it standard behavior of the "my location"-button to work only when GPS is enabled?
I would like to show the rough position on the map, even GPS is disabled. Do I have to use the LocationManager to accomplish this?
Thanks
Upvotes: 2
Views: 4280
Reputation: 11756
With Android Maps API V2, you can use the LocationSource
and LocationSource.OnLocationChangedListener
to pass in your own location updates and control the location that is shown on the map.
For example, you can listen to GPS_PROVIDER
or NETWORK_PROVIDER
location updates via a normal LocationListener
, and pass these locations to the LocationSource.OnLocationChangedListener
. Whatever you pass in is what gets shown on the map.
First, declare an OnLocationChangedListener
object in your Activity
:
private OnLocationChangedListener mListener; //Used to update the map with new location
Then, implement LocationSource for your activity, something like:
public class MapScreen extends FragmentActivity implements LocationSource {
In onCreate()
, set up the LocationSource
for this Activity
when you're setting up the Map object:
...
// Show the location on the map
mMap.setMyLocationEnabled(true);
// Set location source
mMap.setLocationSource(this);
...
Then, add the methods required for the LocationSource
interface:
/**
* Maps V2 Location updates
*/
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
}
/**
* Maps V2 Location updates
*/
@Override
public void deactivate() {
mListener = null;
}
The final part is passing in the location updates from a normal LocationListener
to the Activity
implementing the LocationSource
:
//Update real-time location on map
if (mListener != null) {
mListener.onLocationChanged(location);
}
If you're listening to the GPS_PROVIDER
and passing locations from this provider into the mListener.onLocationChanged()
method, and you turn off GPS, if you don't take any further actions with the LocationSource
, the most recent GPS location will remain on the screen. At this point you can listen to the NETWORK_PROVIDER
and pass these location updates to the mListener.onLocationChanged()
method.
Upvotes: 5
Reputation: 4561
It looks like you must request for location updates. Even if you don't use the incoming location in your code, the blue dot appears.
Upvotes: 0
Reputation: 2380
You need to cache the last known location and show it when you dont have gps on or gps not available.
Upvotes: 1