Google Maps onResume - android

i'm using google maps in my android app. Everything is fine but when i have no GPS service enabled i show a snackbar message to enable. When i enable GPS and turn back in my Fragment der map dosen't return to my location automaticly only when i press the location button.
I tried to solve the problem by using a thread in my update method but nothing. changed. Sometimes it works but sometimes isn't good enough.
my onCreate:
public void init(){
gps = new GPSTracker();
gps.init(mActivity,mActivity);
if (!gps.canGetLocation()) {
gps.showSettingsAlert(mActivity,rootView);
}else {
initMap();
}
my initMap
private void initMap(){
try {
MapsInitializer.initialize(mActivity.getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
moveSearchCircle(new LatLng(gps.getLatitude(), gps.getLongitude()));
updateMapPosition();
googleMap.setIndoorEnabled(true);
addMarker();
}
});
}
updateMapPosition
private void updateMapPosition(){
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(), gps.getLongitude()), 15));
}
onResume
#Override
public void onResume() {
super.onResume();
init();
}

Maybe gps.getLatitude(), gps.getLongitude() returns zero values, and focus of your map's camera trying to set to this place.
Usually, get device location operation takes some time and you should do this asynchronously.
So, please, check your GPSTracker class and find async methods, or see this tutorial.

Related

How can I get current location on mapview using fragment class?

Hello I am new in android development and i want to get current location in mapview using fragment class. when i am adding setMyLocationEnabled method it is asking for permissions and i have added all the permissions in manifest. Please help me .
Gmaps.java (fragment)
public class Gmaps extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
private boolean mapsSupported = true;
private GoogleApiClient mGoogleApiClient;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapsInitializer.initialize(getActivity());
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
double latitude = 0.00;
double longitude = 0.00;
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker");
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(0, 0)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FrameLayout p = (FrameLayout) inflater.inflate(R.layout.fragment_gmaps, container, false);
mapView = (MapView) p.findViewById(R.id.map);
return p;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
In Manifest, I have added all these permissions used for google map services
According to the documentation:
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
That's the reason why althought you have declared the permissions in your manifest file you still need to ask for them at runtime.
As a workaround you can set a minSdkVersion < 23, but also as the documentation says:
Note: Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it's missing a needed permission, regardless of what API level your app targets.
Also, according to the Permissions Best Practices you should test against both permission models to provide a better user experience.
Try this:
public void showMap() {
mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
if (map == null) {
map = mapFragment.getMap();
}
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
latitude= location.getLatitude();
longitude=location.getLongitude();
LatLng loc = new LatLng(latitude, longitude);
if (marker!=null){
marker.remove();
}
marker= map.addMarker(new MarkerOptions().position(loc).title("Sparx IT Solutions"));
map.moveCamera(CameraUpdateFactory.newLatLng(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getActivity().getBaseContext(), "Gps is turned off!!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getActivity().getBaseContext(), "Gps is turned on!! ",
Toast.LENGTH_SHORT).show();
}
add these uses-permissions in Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Android google maps crashes after fragment navigation

I have an app with a navigation drawer and uses fragment to display new screens after user selects a nav item
The part of my MainActivity class that handles that looks like this:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_new) {
addFragment(new NewFragment(), id);
} else if (id == R.id.nav_start) {
addFragment(new StartFragment(), id);
} else if (id == R.id.nav_delete) {
addFragment(new DeleteFragment(), id);
} else if (id == R.id.nav_gps) {
addFragment(new GPSFragment(), id);
}
...
And the addFragment method looks like this:
public void addFragment(Fragment fragment, int id) {
if (fragment != null) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.getFragments() == null) {
fragmentTransaction.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
.commit();
} else {
fragmentTransaction.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
.addToBackStack(Integer.toString(id))
.commit();
}
}
}
One of the fragments is a GPS one where I have implemented google maps. It works, but there are 2 major problems with it and I'm not sure what's going on:
When I navigate to GPS, then to another fragment, then to GPS (repeated multiple times) using the nav drawer, eventually the screen will turn black and completely reload the MainActivity
When I navigate around using the back button (from GPS to another fragment, back to GPS, repeated many times), or use the home button to pause the app and bring it back to resume (repeated multiple times) the app gets extremely slow and takes about a minute to respond to any user input
This must be due to the way I've implemented google maps, or more specifically the way I handle the transition between different states (maybe). I thought that with the way I've implemented my code, whenever I use the nav drawer, or press the back button, or press home to leave the GPS fragment, gmaps will disconnect and the fragment be suspended.
I'm not sure why that would lead to such slowdowns, or a restarting of the app back to the MainActivity. Maybe a memory issue? I'm not sure what would be causing that if I'm always disconnecting from gmaps and removing the fragment when I navigate away. I don't think this was a problem before I added the code to get mMapView.getMapAsync(this) working, so maybe its related to the mapready event and how it interacts with navigation?
The GPSfragment simply listens for changes in lat,lon positions and moves the camera and marker to center the users location. Here is the GPSFragment class:
public class GPSFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback {
private GoogleMap googleMap;
private GoogleApiClient mGoogleApiClient;
double lat, lon;
LocationRequest mLocationRequest;
CoordinatorLayout coordinatorLayout;
UiSettings mapSettings;
CameraPosition cameraPosition;
MarkerOptions markerOptions;
Marker marker;
Location mLastLocation;
MapView mMapView;
public GPSFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
coordinatorLayout = (CoordinatorLayout) getActivity().findViewById(R.id.coordinator_layout);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_gps, container, false);
//Set the nav drawer item highlight
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.navigationView.setCheckedItem(R.id.nav_gps);
//Set actionbar title
mainActivity.setTitle("GPS");
//Create api connector and map
buildGoogleApiClient();
mMapView = (MapView) view.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
//mMapView.onResume();
//When map is ready, set it up with a onMapReady callback
mMapView.getMapAsync(this);
return view;
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
mMapView.onResume();
} else {
mGoogleApiClient.connect();
mMapView.onResume();
}
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
mMapView.onPause();
mGoogleApiClient.disconnect();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mGoogleApiClient.isConnected()) {
mMapView.onDestroy();
mGoogleApiClient.disconnect();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
if (mGoogleApiClient.isConnected()) {
mMapView.onLowMemory();
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
marker.setPosition(new LatLng(lat, lon));
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(new LatLng(lat, lon)));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
//Request permission for location data
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//If permission has not been granted
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
//If they have previously declined permission, show explanation
Snackbar.make(coordinatorLayout, R.string.permission_explain_gps,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.request_permission, new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);
}
}).show();
} else {
//If no previous declines
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);
}
} else {
//If permission has been granted
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
#Override
public void onMapReady(GoogleMap mMapView) {
googleMap = mMapView;
setupMap();
}
public void setupMap() {
mapSettings = googleMap.getUiSettings();
mapSettings.setZoomGesturesEnabled(true);
mapSettings.setZoomControlsEnabled(true);
mapSettings.setScrollGesturesEnabled(true);
mapSettings.setTiltGesturesEnabled(true);
mapSettings.setRotateGesturesEnabled(true);
markerOptions = new MarkerOptions().position(new LatLng(lat, lon));
marker = googleMap.addMarker(markerOptions);
cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lon)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
EDIT: also just noticed that after closing and uninstalling the app from my phone, the map marker icon is still in my status bar at the top, which I think only comes on when the phone is currently requesting location information...

getProjection().getVisibleRegion().latLngBounds; returns 0 after onMapReady

I am trying to get the LatLngBounds from the Visible Region on the device's screen after my Google map has been initialized. However I only receive a 0 values. My guess is that the map has not actually been loaded, even after OnMapReady has been called. I've looked all over for a better way of checking for map initialization and found nothing. How do I ensure I receive the correct data?
INITIALIZE MAP
public void initMap(){
MapFragment map = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
map.getMapAsync(this);
}
ON MAP READY CALLBACK
#Override
public void onMapReady(GoogleMap googleMap) {
try {
if (googleMap != null) {
mGoogleMap = googleMap;
mGoogleMap.setOnMarkerClickListener(this);
mGoogleMap.setOnCameraChangeListener(this);
mGoogleMap.setOnMapClickListener(this);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
search();
}
} catch (Exception exception) {
mUtility.getThemedAlert(this,
getResources().getString(R.string.error_google_maps),
getResources().getString(R.string.unable_build_google_maps)).show();
}
}
GET BOUNDS
public void search() {
LatLngBounds bounds = mGoogleMap.getProjection().getVisibleRegion().latLngBounds;
Log.e("TEST", bounds.toString());
}
LOG OUTPUT
E/TESTīš• LatLngBounds{southwest=lat/lng: (0.0,0.0), northeast=lat/lng: (0.0,0.0)}
OnMapLoaded function helps. Thank you.
Here is my code,
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
invokeApi();
}
});

Change zoom level Google Maps Api v2 on app start

Is it possible to change the zoom level as soon as the map is ready? When I open the app it shows the map and the blue dot for my location. However, the zoom level is the default 3. How can I change this? I know how to do it when the 'MyLocationButton'is clicked but not when the app starts.
This is my class
public class MainPhoneActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationSource, LocationListener, OnMyLocationButtonClickListener, OnMapReadyCallback{
private GoogleApiClient mGoogleApiClient;
private OnLocationChangedListener mMapLocationListener = null;
// location accuracy settings
private static final LocationRequest REQUEST = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_phone);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
#Override
public void onMapReady(GoogleMap map) {
map.setLocationSource(this);
map.setMyLocationEnabled(true);
map.setOnMyLocationButtonClickListener(this);
}
public void showMyLocation(View view) {
if (mGoogleApiClient.isConnected()) {
String msg = "Location = "
+ LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
if (mMapLocationListener != null) {
mMapLocationListener.onLocationChanged(location);
}
}
#Override
public void onConnected(Bundle connectionHint) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, REQUEST,this);
}
#Override
public void onConnectionSuspended(int cause) {
// Do nothing
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
return false;
}
#Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mMapLocationListener = onLocationChangedListener;
}
#Override
public void deactivate() {
mMapLocationListener = null;
}
}
You can set zoom level like following:
map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
Where point is your LatLng position. In this way you can center the map in that point with given zoom level.
Complete method:
#Override
public void onMapReady(GoogleMap map) {
map.setLocationSource(this);
map.setMyLocationEnabled(true);
map.setOnMyLocationButtonClickListener(this);
//newLatLngZoom(LatLng , ZoomLevel) -> choose your zoom level
// and change my 'point' with yours
map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
}
EDIT:
If you want to get the dot coords, you can try this:
Location loc = map.getMyLocation();
LatLng point = new LatLng(loc.getlatitude() , loc.getLongitude());
and use that point as center.
Complete method:
#Override
public void onMapReady(GoogleMap map) {
map.setLocationSource(this);
map.setMyLocationEnabled(true);
map.setOnMyLocationButtonClickListener(this);
Location loc = map.getMyLocation();
if(loc != null){
LatLng point = new LatLng(loc.getLatitude() , loc.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
}
}
This could cause a NullPointerException beacuse loc could be null.
OTHER SOLUTION
If you want to get only first time the coordinates, you should work in onLocationChanged, using a boolean variable to set first call.
Declare it CRDS_CALL = false;
#Override
public void onLocationChanged(Location location) {
if (mMapLocationListener != null) {
mMapLocationListener.onLocationChanged(location);
if(!CRDS_CALL){
LatLng point = new LatLng(location.getLatitude(), location.getLognitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
CRDS_CALL = true;
}
}
}
In this answer i use map, but you have to use your mapFragment, but if you want to use it in other methods over onCreate, you have to declare outside of it.
Add this just before the onCreate
SupportMapFragment mapFragment;
And inside it, use it like follwing:
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
In that way, you can use mapFragment in other methods
Solution
The solution was to do everything #MikeKeepsOnShine said but remove the
Location loc = map.getMyLocation();
LatLng point = new LatLng(loc.getLatitude() , loc.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
part from onMapReady. Works absolutely perfectly now!
You should use this. And you should put this request in onMapReady() callback. Something like this:
#Override
public void onMapReady(GoogleMap map) {
map.setLocationSource(this);
map.setMyLocationEnabled(true);
map.setOnMyLocationButtonClickListener(this);
map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
}
you have already done the new "MapAsync" way so you are one step forward to the result.
In order to zoom, you can use the animateCamera method for googleMap object to zoom to a specific location:
https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#animateCamera(com.google.android.gms.maps.CameraUpdate)
for example, a zoomin:
map.animateCamera(CameraUpdateFactory.zoomIn());
or if you already know "where":
map.animateCamera(CameraUpdateFactory.newLatLngZoom(knownlocation,17));
and you will be very close to the location.
If you need to do at the first "locationUpdate" you should keep a flag to false and set to true the first time you receive a location, at that time you perform the zoom to location.
EDIT: If you want to zoom only the first time, where you receive location updates (which is not really clear from your code), you can do, assuming you have a class variable like:
private boolean FIRST_TIME = true;
the following code:
if(FIRST_TIME){
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location,17));
FIRST_TIME = false;
}
The best option is to remove the listener but it seems you use location updates as "blue dot" updates.
What worked for me was:
mMap.setMinZoomPreference(6.0f);
mMap.setMaxZoomPreference(20.0f);
You can modify the zoom preference values to your taste.

GPS tracker with GoogleApiClient

in the last update of google services, Google has depercated LocationClient api and now say use GoogleApiClient.
Now need create the App with GPS report any 30 seconds to my webserver but dont found (or dont understant) how work this new api.
If you have a example using GoogleApiClient please past the link to see or download.
And if have a Service with GoogleApiClient please past the link
Thanks for your help.
If you have installed android sdk then just checkout following directory \extras\google\google_play_services\samples\maps\src\com\example\mapdemo\.
It is having one example of showing current location in GoogleMap and it is using GoogleApiClient to retrieve current location on periodic interval of 5 seconds as described in following code. You can modify it according to your requirements.
MyLocationDemoActivity.java
public class MyLocationDemoActivity extends FragmentActivity
implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
OnMyLocationButtonClickListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private TextView mMessageView;
// These settings are the same as the settings for the map. They will in fact give you updates
// at the maximal rates currently possible.
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_demo);
mMessageView = (TextView) findViewById(R.id.message_text);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpGoogleApiClientIfNeeded();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
}
}
private void setUpGoogleApiClientIfNeeded() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
}
/**
* Button to get current Location. This demonstrates how to get the current Location as required
* without needing to register a LocationListener.
*/
public void showMyLocation(View view) {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
String msg = "Location = "
+ LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
/**
* Implementation of {#link LocationListener}.
*/
#Override
public void onLocationChanged(Location location) {
mMessageView.setText("Location = " + location);
}
/**
* Callback called when connected to GCore. Implementation of {#link ConnectionCallbacks}.
*/
#Override
public void onConnected(Bundle connectionHint) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
REQUEST,
this); // LocationListener
}
/**
* Callback called when disconnected from GCore. Implementation of {#link ConnectionCallbacks}.
*/
#Override
public void onConnectionSuspended(int cause) {
// Do nothing
}
/**
* Implementation of {#link OnConnectionFailedListener}.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}
I had exactly your same problem. You need to explicitely use GoogleMap.setLocationSource().
Here is an example: Android: Google Maps location with low battery usage

Categories

Resources