Cannot Zoom Android Map fragment to the current location - android

This is not the first question im posting regarding this matter in Stack Overflow. I really need help to zoom my map fragment to the current location. Please don't think I'm not trying anything. I tried a lot.
I need to zoom my map to the current location and no matter how hard I tried map zoom to another location not my current location. Cannot even possibly think what is happening here.
Here is my GoogleMapsFragment.java
public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
View rootView;
private GoogleApiClient mGoogleApiClient;
private GoogleMap map;
private LatLng latlng;
public GoogleMapsFragment()
{
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(!isGooglePlayServiceAvailable())
{
return null;
}
if(rootView != null)
{
ViewGroup parent = (ViewGroup)rootView.getParent();
if(parent != null)
{
parent.removeView(rootView);
}
}
else
{
rootView = inflater.inflate(R.layout.google_maps, container, false);
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null)
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
return rootView;
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng));
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean isGooglePlayServiceAvailable()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS == status)
{
return true;
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
//Zoom to the current location
public Location getMyLocation() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
return location;
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(true);
}
#Override
public void onConnected(Bundle bundle) {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
}
I think I've dome a small mistake and it zooms to another location and it is not even close to my country.
Here is the image of my zooming location.
Someone please tell me how to zoom my map fragment to the current location.
Any kind of help may appreciated. :)
~ Edit for Gaurav ~
Added getMyLocation() inside onMapReady()
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
getMyLocation();
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(true);
}
~ Edited full code ~
public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
View rootView;
private GoogleApiClient mGoogleApiClient;
private GoogleMap map;
private LatLng latlng;
public GoogleMapsFragment()
{
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(!isGooglePlayServiceAvailable())
{
return null;
}
if(rootView != null)
{
ViewGroup parent = (ViewGroup)rootView.getParent();
if(parent != null)
{
parent.removeView(rootView);
}
}
else
{
rootView = inflater.inflate(R.layout.google_maps, container, false);
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null)
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
return rootView;
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng));
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean isGooglePlayServiceAvailable()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS == status)
{
return true;
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
//Zoom to the current location
public Location getMyLocation() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
return location;
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
Location myLocation = getMyLocation();
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
latLng
, 15));
}
private LocationRequest mLocationRequest;
private static final long INTERVAL = 1000 * 1000;
private static final long FASTEST_INTERVAL = 1000 * 900;
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
}
~ Error Log ~
06-16 11:23:28.180 6647-6647/com.myayubo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.myayubo, PID: 6647
java.lang.NullPointerException
at com.myayubo.GoogleMapsFragment.onMapReady(GoogleMapsFragment.java:151)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzl$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:361)
at com.google.android.gms.maps.internal.v$a$a.a(:com.google.android.gms.alldynamite:82)
at maps.ei.bu$6.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)

Here it is:
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
Location myLocation = getMyLocation();
LatLng latLng = new LatLng(myLocation.getlatitude(), myLocation.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
latLng
, 15));
}
and
private LocationRequest mLocationRequest;
private static final long INTERVAL = 1000 * 1000;
private static final long FASTEST_INTERVAL = 1000 * 900;
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
this will call onLocationChanged();

Try calling onLocationChanged(), from within getMyLocation()

Firstly check whether you are receiving location coordinates values or not, if receiving try using this one
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
This could be useful for you.

Related

separate map from location doesn't update location onCreate

This is the getDeviceLocation I am currently using.
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
SET_LOCATION_STATUS = 1;
mMap.clear();
// Set the map's camera position to the current location of the device.
mLastKnownLocation = location;//task.getResult();
// showMap() method starts
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
//showMap() method ends
latlang.Lat = mLastKnownLocation.getLatitude();
latlang.Lang = mLastKnownLocation.getLongitude();
} else {
...}
I was trying to separate the location from the map part using another method as:
/*
Attempt to seperate location and map
*/
private void showMap(){
if(MAP_LOCATION_SOURCE == 1){
getDeviceLocation();
}
if (SET_LOCATION_STATUS ==1 ) {
mMap.clear();
Log.v("Location Available??????????", Double.toString(latlang.Lat));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(latlang.Lat, latlang.Lang), DEFAULT_ZOOM));
marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latlang.Lat, latlang.Lang))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
}
}
They are called/used as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
SET_LOCATION_STATUS = 1;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_second, null, false);
onSaveInstanceState(new Bundle());
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
getLocationPermission();
getDeviceLocation();
// showMap();
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
getLocationPermission();
updateLocationUI();
getDeviceLocation();
// showMap();
This is working without any error, but doesn't take the location/camera position from Bundle as in the case when map is inside the getDeviceLocation. When I use start using the app, the location and map get updated.
How I can separate the location and map properly then?

In Google Maps, why is OnLocationChanged() not called again, when the app is maximized from its minimized state?

I am developing an Android Application. In that I integrated Google Maps in a Fragment .
My Problem
In the Map , in normal running state , OnLocationChanged function called by LocationListener and my Map Marker is moving correctly.
But , if I minimizes the app and after I maximize it , the marker is not moving . I checked and found , the OnLocationChanged not get called after Maximizing the App.
So I put some Log.D commends in the onLocationChanged and reran it.
Until minimizing the App , The Log commends exectuted on each and every location changed. But After I minimized and maximized the App , The Log printing stoped and marker stopped moving.
My Efforts to Resolve
I tried implementing OnResume method in Fragment but it not called.
So I searched the internet. Based on the suggestions I recreated the Fragment on the onResume method of the parent Activity of the Fragment.
After that , the the tracking worked even after resuming. But I fell in to an another problem.
When the Fragment get Recreated in the onResume() of the parent Activity , the Map loading the from the beginning. That is the Map showing Whole world map..... then slowly it goes to current location and the old markers cleared and new markers draw again. After that marker start moving.
So that process takes long time.
Now I can't move further. Since I am new to Google Maps I can't fix it..
My Code:
Map_Fragment.java
/**
* A simple {#link Fragment} subclass.
*/
public class Map_Fragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, LocationSource,
GoogleApiClient.OnConnectionFailedListener, GeoQueryEventListener, ValueEventListener,LocationListener {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private GoogleMap mMap;
LocationManager locationManager;
RelativeLayout toolbarLayout;
String driverId = "5acgh565733";
RelativeLayout progressLayout1, progresslayout, onlinelay;
String tripState, onlinecheck;
FrameLayout fragmentcontainer;
TextView onlineTxt;
SharedPreferences.Editor editor;
String onlinestatus;
View mapView;
Bitmap mapBitmap;
Marker mCurrLocationMarker;
CameraUpdate cameraUpdate = null;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private OnLocationChangedListener mMapLocationListener = null;
LocationRequest mLocationRequest;
Dialog d, dialogTripSummary, dialog;
ProgressWheel pwOne;
ImageView requestMapView;
ArrayList<LatLng> MarkerPoints;
Location mCurrentLocation, lStart, lEnd;
RelativeLayout FAB;
GeoFire geoFire;
BottomBar bottomBar;
boolean clicked = false;
public Map_Fragment() {
// Required empty public constructor
}
#SuppressLint("CommitPrefEdits")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
toolbarLayout = view.findViewById(R.id.toolbar);
onlinelay = view.findViewById(R.id.onlinelay);
onlineTxt = view.findViewById(R.id.onlineTxt);
FAB = view.findViewById(R.id.myLocationButton);
toolbarLayout.setVisibility(View.VISIBLE);
bottomBar=(BottomBar)getActivity().findViewById(R.id.bottomBar);
editor = this.getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, getActivity().MODE_PRIVATE).edit();
if(mCurrentLocation!=null){
LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to current location
.zoom(15)
.tilt(0) // Sets the tilt of the camera to 0 degrees
.build();
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.car))
.position(latLng));
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
checkOnlineStatus();
}
fabmethod();
onlinelay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getActivity(), "Online Clicked", Toast.LENGTH_SHORT).show();
setOnlineStatus();
}
});
return view;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(mCurrentLocation!=null){
LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to current location
.zoom(15)
.tilt(0) // Sets the tilt of the camera to 0 degrees
.build();
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.car))
.position(latLng));
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
Log.D(TAG,"You moved.. The current lat is "+location.getLatitude());
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.car));
mCurrLocationMarker = mMap.addMarker(markerOptions);
updateLocationToFirebase(location);
}
#Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mMapLocationListener = onLocationChangedListener;
}
#Override
public void deactivate() {}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getMinZoomLevel();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
FAB.setVisibility(View.INVISIBLE);
toolbarLayout.setVisibility(View.INVISIBLE);
bottomBar.setVisibility(View.GONE);
}
});
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
FAB.setVisibility(View.VISIBLE);
bottomBar.setVisibility(View.VISIBLE);
toolbarLayout.setVisibility(View.VISIBLE);
}
});
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
// mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
//mMap.setMyLocationEnabled(true);
}
// System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation);
if(mCurrentLocation!=null){
LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to current location
.zoom(15)
.tilt(0) // Sets the tilt of the camera to 0 degrees
.build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, Map_Fragment.this);
}
}
}
Toast.makeText(getActivity(),"Retriving current location. Please Wait...",Toast.LENGTH_LONG).show();
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
public void fabmethod() {
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurrentLocation != null) {
LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
System.out.println("INSIDE LOCAION CHANGE" + mCurrentLocation.getLatitude() + mCurrentLocation.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to current location
.zoom(15)
.tilt(0) // Sets the tilt of the camera to 0 degrees
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
else{
Toast.makeText(getApplicationContext(),"mmap not Added", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
In the above Program , the onLocationChanged not called after resuming.
MainActivity.java
public class MainActivity extends FragmentActivity {
BottomBar bottomBar;
Fragment fragment =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
bottomBar = (BottomBar) findViewById(R.id.bottomBar);
bottomBar.setVisibility(View.VISIBLE);
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if (tabId == R.id.tab_profile) {
fragment = new Viewprofile_Fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
if (tabId == R.id.tab_rating) {
fragment = new Ratings_Fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
if (tabId == R.id.tab_earning) {
fragment = new Earnings_Fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
if (tabId == R.id.tab_home) {
fragment = new Map_Fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
});
}
#Override
public void onResume(){
super.onResume();
fragment = new Map_Fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
In the above program, the onResume() ,method recreates the Map since
the Fragment recreated. So the Map takes time to load.
Final Words
Please Help me to enable Tracking location continuously even after maximizing the App
if ( mGoogleApiClient!=null && mLocationRequest!=null )
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
add this code in onResume() method of MapActivity.

Google maps v2 not initializing in fragment

I want to show my current location using Google maps v2 from a fragment however the Google maps is not initializing on start up. When i run the application, it is nor crashing but the map is not showing my current location neither is it displaying anything. I have used this code on my activity and it is fully functional.
Below is my java code:
public class MapFragment extends Fragment implements LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,OnMapReadyCallback {
SupportMapFragment mSupportMapFragment;
MapView mMapView;
Location mLastLocation;
Marker mCurrLocationMarker;
private MarkerOptions markerOptions;
protected GoogleApiClient mGoogleApiClient;
private LatLng latLng;
public GoogleMap mMap;
private Marker marker;
LocationRequest mLocationRequest;
private GoogleMap googleMap;
private TextView lastTrip, lastDeliveryText, lastDelivery, lastAmountText, lastAmount, kes,
todayTotal, totalDeliveryText, totalDelivery, totalAmount, totalAmountText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
buildGoogleApiClient();
// inflat and return the layout
View v = inflater.inflate(R.layout.map_fragment, container,
false);
mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null) {
mSupportMapFragment.getMapAsync(this);
}
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("one","one");
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//mMap.getUiSettings().setZoomControlsEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.d("two","two");
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
Log.d("three","three");
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
Log.d("four","four");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Log.d("five","five");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//mMap.getUiSettings().setZoomControlsEnabled(true);
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
Log.d("LATLANGz", lat + "|" + lng);
latLng = new LatLng(lat, lng);
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Positionn");
if (ActivityCompat.checkSelfPermission(getActivity(), 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;
}
mMap.setMyLocationEnabled(false);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_location));
marker = mMap.addMarker(markerOptions);
//move map camera_main
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onResume() {
super.onResume();
Log.d("hey2","hey2");
// mMapView.onResume();
mSupportMapFragment.onResume();
}
#Override
public void onPause() {
super.onPause();
Log.d("hey1","hey1");
// mMapView.onPause();
mSupportMapFragment.onPause();
}
/* #Override
public void onDestroy() {
super.onDestroy();
// mMapView.onDestroy();
mSupportMapFragment.onDestroy();
}*/
#Override
public void onLowMemory() {
super.onLowMemory();
// mMapView.onLowMemory();
mSupportMapFragment.onLowMemory();
}
#Override
public void onDetach() {
Log.d("detach", "detach");
super.onDetach();
mSupportMapFragment.onDetach();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("six","six");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (mGoogleApiClient.isConnected()){
Log.d("seven","six");
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
first of all Chaeck permission in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
then check method for current location
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
marker = map.addMarker(new MarkerOptions().position(loc));
if(map != null){
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
then use
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
and be patience map take laoding time depend on you network speed
comment if any query
First check your permissions and your google api key in your manifest
Your xml layout must be something like this without any thing else:
. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.isg_biz.isg_tracking.MainActivity" />
You have to implement OnMapReadyCallback, then
your code should be something like this in onCreate() :
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Do not to copy and past the same xml code literally you have to change (tools : .....) to same that exist in your xml
for documentation, java code & more Please read :
https://developers.google.com/maps/documentation/android-api/map-with-marker

I can't get the location from locationlistener

I used a Fragment implements LocationListener and i tried to get my current location , but i can't get it successfully. Do i miss something ?
public class TrafficInformation extends Fragment implements LocationListener{
private MapView mapView;
private GoogleMap googleMap;
private double myLatitude,myLongitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.traffic_information_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
//part of android 6.0 permission
int flag = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (flag != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
googleMap.setMyLocationEnabled(true);
}
// For dropping a marker at a point on the Map
//i set my current location over here-------------------
LatLng sydney = new LatLng(myLatitude, myLongitude);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
//For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(16).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return view;
}
i try to get it from this function:
#Override
public void onLocationChanged(Location location) {
myLatitude=location.getLatitude();
myLongitude=location.getLongitude();
}
i can't get myLatitude and myLongitude location , why?
any help would be grateful.
You are not calling
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this)
You are only calling
googleMap.setMyLocationEnabled(true);
This don't request for location updates... just set a pin on your position on the map.
Check here to see how to request current location:
https://developer.android.com/training/location/receive-location-updates.html

getLastLocation() always null in GoogleApiClient

Am trying to build an application that requests the current location using the GoogleClientApi and LocationServices, but the Location is always null even that I enabled the WiFi,Mobile Data and GPS , tested it on several devices all the same
the permissions from the manifest.xml :
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Activity:
public class FindStation extends Fragment implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,com.google.android.gms.location.LocationListener
{
public static FragmentManager fragmentManager;
Button goButton;
Spinner spinner;
SupportMapFragment mapFragment;
GoogleMap map;
List<Stations> stationsList;
ArrayList<String> stationsAddresses;
private static View view;
ArrayList<MarkerOptions> markers;
GoogleApiClient mGoogleApiClient;
LocationServices locationServices;
Location location;
private static String TAG="FIND_STATION";
Context context;
LocationRequest mLocationRequest;
LocationListener locationListener;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
context= getActivity();
locationListener=this;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(10);
/*mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();*/
buildGoogleApiClient();
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.activity_find_station, container, false);
} catch (InflateException e) {
}
inflater.inflate(R.layout.activity_find_station,container,false);
stationsAddresses = new ArrayList<>();
goButton= (Button) view.findViewById(R.id.button);
//goButton.setVisibility(View.INVISIBLE);
spinner= (Spinner) view.findViewById(R.id.spinner);
stationsList = Stations.listAll(Stations.class);
markers = new ArrayList<>();
for (int i = 0; i <stationsList.size() ; i++) {
stationsAddresses.add(stationsList.get(i).getStationLocation());
markers.add(new MarkerOptions().position(new LatLng(stationsList.get(i).getStationLat(), stationsList.get(i).getStationLong())).title(stationsList.get(i).getStationName()));
}
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//location= LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
});
try {
initialize();
} catch (Exception e) {
e.printStackTrace();
}
try {
// map.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
/*thread = new Thread(new MyThread());
thread.start();*/
return view;
}
private void initialize() {
if (map==null) {
Fragment fragment= getChildFragmentManager().findFragmentById(R.id.map);
mapFragment= (SupportMapFragment) fragment;
map=mapFragment.getMap();
for (int i = 0; i <markers.size() ; i++) {
map.addMarker(markers.get(i));
}
// check if map is created successfully or not
if (map==null) {
Toast.makeText(super.getActivity(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
public void onDestroyView() {
super.onDestroyView();
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
SupportMapFragment fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (fragment!=null) {
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.remove(fragment);
ft.commit();
}
}
#Override
public void onConnected(Bundle bundle) {
location= LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location!=null){
Log.d(TAG,location.toString());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),3f);
map.animateCamera(update);
}
Log.d(TAG,"connected");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG,"connection suspended "+String.valueOf(i));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG,"connection failed");
}
#Override
public void onLocationChanged(Location location) {`enter code here`
Log.d(TAG,location.toString());
this.location=location;
if (location!=null) {
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 3f);
map.animateCamera(update);
Log.d(TAG, "camera updated to new position");
goButton.setVisibility(View.VISIBLE);
}
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
Log.d(TAG,"connect() was called");
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
the strange thing is that the onConnect() method is called but after that the Location is always null and onLocationChanged() is never called
using the maps, i tried the enabling my location and it works when you have the button on the right top corner it returns the location and animates the camera.
UPDATE 1
updated the onConnected() method and made it request locations updates,
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener);
if (location!=null){
Log.d(TAG,location.toString());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),3f);
map.animateCamera(update);
}
Log.d(TAG,"connected");}
then with a button i call lastKnownLocation() since the onLocationChanged() is not called still, and still the returned Location is null
UPDATE 2 :
The very same code worked on Android 5.0.1 and worked perfectly
all the other devices was on android 2.3.7,4.0.1 none of them worked,
Any idea about what difference in the Android APIs regarding the location?
You need to call requestLocationUpdates() in order to register the listener and have onLocationChanged() invoked.
Be sure to un-register the listener as soon as possible to avoid excessive battery drain.
Also note that the getLastLocation() method can and will return null. The main problem is that it doesn't prompt a request to the OS for a new location lock, instead it just checks if there was a last known location from some other app's location request. If no other app had recently made a location request, then you get a null location returned to you.
The only way to guarantee that you actually get a location is to request one, and this is done with a call to requestLocationUpdates().
Here is a working example for reference:
public class MainActivity extends FragmentActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap map;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
buildGoogleApiClient();
mGoogleApiClient.connect();
if (map == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap retMap) {
map = retMap;
setUpMap();
}
public void setUpMap(){
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected",Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//remove previous current location Marker
if (marker != null){
marker.remove();
}
double dLatitude = mLastLocation.getLatitude();
double dLongitude = mLastLocation.getLongitude();
marker = map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
}
One more thing, if your map is in a Fragment, there is no need to have a nested SupportMapFragment. You can just have your Fragment extend SupportMapFragment. This removes the need of having a nested Fragment, and you don't even need to inflate any layout xml, here is a simple example:
public class MapTabFragment extends SupportMapFragment
implements OnMapReadyCallback {
private GoogleMap mMap;
private Marker marker;
public MapTabFragment() {
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
});
}
}

Categories

Resources