I want to display AlertDialogue onMapReady. I implemented the alert dialogue in other class and it working fine.
When I add the alert dialogue code in the MapsActivity which is extending FragmentActivity, it doesn't work as intended to be.
When I run the activity, the AlertDialogue does show up with the button. But, title and message doesn't show
public class MapsActivity extends FragmentActivity implements GoogleMap.OnCameraIdleListener,OnMapReadyCallback {
private GoogleMap mMap;
private Location currentLocation;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int LOCATION_REQUEST_CODE =101;
private static final String Log_TAG = "Maps_Log_Tag_Results";
private Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
return;
}
fetchLastLocation();
}
private void fetchLastLocation(){
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
SupportMapFragment supportMapFragment= (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1);
supportMapFragment.getMapAsync(MapsActivity.this);
}else{
Toast.makeText(MapsActivity.this,"No Location recorded",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(onMyLocationButtonClickListener);
mMap.setOnMyLocationClickListener(onMyLocationClickListener);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.setMyLocationEnabled(true);
mMap.setOnCameraIdleListener(this);
LatLng latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,13));
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hello");
builder.setMessage("This is alert dialogue");
// add the buttons
builder.setPositiveButton("Awesome", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
}
}
I think it has something to do with the FragmentActivity, because in alert dialogue in ActivityCompat work just fine.
Try to change
MainActivity extends FragmentActivity
to be
MainActivity extends AppCompatActivity
Related
I'm building an app, and I run on a problem with Google Maps. I wrote most of the code, but I don't how how to set that when user clicks on item(method onItemClick), in my case I have ListView on Firebase that is showing Tours of concerts, which you can see here:my tours listview to open a specific place and show it on map. For example, user clicks on Anaheim, CA concert and it shows where that place is. Thanks in advance.
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int REQUEST_LOCATION_PERMISSION = 10;
private GoogleMap.OnMapClickListener mCustomOnMapClickListener;
private GoogleMap mGoogleMap;
private MapFragment mMapFragment;
#BindView(R.id.lvTours) ListView lvTours;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
this.initialize();
}
public void initialize(){
this.mMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fGoogleMap);
this.mMapFragment.getMapAsync(this);
this.mCustomOnMapClickListener = new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
MarkerOptions newMarkerOptions = new MarkerOptions();
newMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tour));
newMarkerOptions.title("Tour");
newMarkerOptions.snippet("It' was here!");
newMarkerOptions.position(latLng);
mGoogleMap.addMarker(newMarkerOptions);
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.mGoogleMap = googleMap;
UiSettings uiSettings = this.mGoogleMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setZoomGesturesEnabled(true);
this.mGoogleMap.setOnMapClickListener(this.mCustomOnMapClickListener);
}
private boolean hasLocationPermission() {
String LocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
int status = ContextCompat.checkSelfPermission(this, LocationPermission);
if (status == PackageManager.PERMISSION_GRANTED) {
this.mGoogleMap.setMyLocationEnabled(true);
return true;
}
return false;
}
private void requestPermission() {
String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(MapActivity.this, permission, REQUEST_LOCATION_PERMISSION);
}
#OnItemClick(R.id.lvTours)
public void onClick()
{
}
}
Since you have your coordinates, you can build a LatLng(latitude, longitude) object
then you can move the camera of your map like this:
build a new camera position using CameraPosition.Builder() and then ask to your mGoogleMap to animate to that position:
CameraPosition position = CameraPosition.builder()
.target(location)
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), null)
using that position you can even put a marker on the map:
mGoogleMap.addMarker(new MarkerOptions().position(position)
.title("some title"));
I'm working on a project where I am switching between two map activities.
The structure I'm attempting is something like this:
BaseMapsActivity extends FragmentActivity
MapsActivity1 extends BaseMapsActivity
MapsActivity2 extends BaseMapsActivity
In order to prevent code duplication. I'd like to put my Google API client code in the base Activity and then some map styling code in the base onMapReady() and simply make changes for each sub activity afterwards (adding markers, etc).
My question is, how can I prepare this mapFragment with style and location logic in the base class, and then inflate a frame layout with the fragment in the sub activities to modify it? How would the steps of this process play out? Is this even possible?
public abstract class BaseMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
public static final String TAG = "BaseMapsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.base_map_activity);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Can't find style. Error: ", e);
}
mMap.moveCamera(CameraUpdateFactory.zoomTo(14));
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
and for the sub activity 1...
public class MapsActivity1 extends BaseMapsActivity implements LocationListener, View.OnClickListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private GoogleMap mMap;
private FirebaseAuth firebaseAuth;
private FirebaseUser user;
private DatabaseReference databaseRef;
private static final String TAG = "MapsActivity1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
and the second activity...
public class MapsActivity2 extends BaseMapsActivity implements OnMapReadyCallback,
View.OnClickListener, OnProgressListener {
// GoogleMap mMap;
private static GoogleMap mMap;
SeekBar colorSeek;
private double longitude;
private double latitude;
private Bundle mapSpots;
private Button backToMap;
private SeekBar.OnSeekBarChangeListener seekBarListener;
private LatLng user;
private static final String TAG = "MapsActivity2";
private static final int HUE_MAX = 360;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
Thanks T
Needed to call super.onMapReady(Bundle savedInstanceState) not in the onMapReady override in the child class, so instead of:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
It needs to be this:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.onMapReady(mMap);
#Override
protected void onMapReady(GoogleMap googleMap){
mMap = googleMap;
super.onMapReady(mMap);
I'm a beginner in android programming and I'm currently working on google maps. What I want to do is to get the current location of the user and then put a marker on that location.
I'm practicing on this but I really can't get it to work. This only shows the current location of the user. But what I want to do is to display a marker on it as well. Any suggestions how to do it?
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
android.Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "Showing current location", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
enableMyLocation();
} else {
mPermissionDenied = true;
}
}
Get you last location-
LatLng location = getLatLngFromLastLocation();
Then use this code block to put marker on map:
MarkerOptions markerOptions = new MarkerOptions()
.position(location)
.icon(getMarkerIcon(mProfileTheme.getColorCodeLight()));
public BitmapDescriptor getMarkerIcon(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
return BitmapDescriptorFactory.defaultMarker(hsv[0]);
}
I'm trying to use Picasso now for my Custom Marker's Images. I was previously using a Bitmap and setting individual Marker's InfoWindow Images with those Bitmaps with the help of a HashMap. But I like how Picasso will cache the Images for me and helps scale them etc.
public class HomeActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener, GoogleMap.OnMapLongClickListener, DetailsDialog.DialogListener, PictureDialog.FinishedMemorySaving {
private GoogleMap mMap;
private LocationManager locationManager;
private Location location;
private String provider, title, desc;
private LatLng latlng;
private Memory memory;
private FragmentManager fm;
private HashMap<String, Memory> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
markers = new HashMap<>();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 400, 1, this);
if(location != null){
Log.i("App Info", "Location found");
} else {
Log.i("App Info", "Location not found");
}
}
//.....OTHER METHODS WORKING DELETED NOT NEEDED FOR THIS.....
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.marker_layout, null);
Bitmap bit = null;
ImageView markerImage = (ImageView)view.findViewById(R.id.markerImage);
TextView markerTitle = (TextView)view.findViewById(R.id.markerTitle);
TextView markerDate = (TextView)view.findViewById(R.id.markerDate);
if(markers != null && markers.size() > 0){
// ADDED THE CALLBACK ALONG WITH MARKER
Picasso.with(getApplicationContext())
.load(markers.get(marker.getId()).getImageMem())
.centerInside()
.fit()
.into(markerImage, new MarkerCallback(marker));
markerTitle.setText(markers.get(marker.getId()).getTitleMem());
markerDate.setText(markers.get(marker.getId()).getFormatedDate());
}
return view;
}
});
}
public void setImages(String markerID, View view){
Log.i("PATH TESTER 2", markers.get(markerID).getImageMem());
}
#Override
public void showMemory(Memory memory) {
String markerID;
Toast.makeText(getApplicationContext(), "The Minions have saved your Memory!", Toast.LENGTH_SHORT).show();
markerID = mMap.addMarker(new MarkerOptions().title(memory.getTitleMem()).position(memory.getLocationMem())).getId();
Log.i("PATH TESTER", memory.getImageMem());
markers.put(markerID, memory);
mMap.moveCamera(CameraUpdateFactory.newLatLng(memory.getLocationMem()));
}
public class MarkerCallback implements Callback {
Marker marker=null;
MarkerCallback(Marker marker) {
this.marker=marker;
}
#Override
public void onError() {
Log.e(getClass().getSimpleName(), "Error loading thumbnail!");
}
#Override
public void onSuccess() {
if (marker != null && marker.isInfoWindowShown()) {
marker.hideInfoWindow();
marker.showInfoWindow();
}
}
}
}
Is there something I'm not doing right? The path is coming through fine and is correct. I've also set an ImageView in a dialog with the same path and it worked. Thanks for any help given.
EDIT:
I now seem to be getting the Error coming up that results in the MarkerCallBack when ever I click on the marker. It doesn't seem to set the actual Image on the marker though :/. Hope someone can help!
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)));
}
});
}
}