In PostExecute i have this array name : locations
I print Log for more details like that:
[lat/lng: (18.5159983333333,-72.2916166666667), lat/lng: (18.5363383333333,-72.3231866666667), lat/lng: (18.5076266666667,-72.3164933333333), lat/lng: (18.54138,-72.2920766666667)]
And i try to show all coordinates like that
protected void onPostExecute(Boolean result) {
dialog.dismiss();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions()
.position(lng)
.title("Test")
.icon(BitmapDescriptorFactory.fromResource(getResources().getIdentifier("Title", "drawable", getPackageName()))));
}
}
Google map shows blank. How may i resolve it please??
You can only add markers when your map is ready to receive them and that is true when
public void onMapReady(GoogleMap googleMap)
is called.
I will try to get you started with this:
You need to setup some variables:
private GoogleMap mMap;
private boolean isMapReady = false;
private ArrayList<LatLng> myLocations = null;
the ArrayList will contain your locations you get from your AsyncTask
Then you need to get the mapOnReady setup in your onCreate() Methode:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// What ever else you need
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapViewRidesFoundMap);
mapFragment.getMapAsync(this);
}
Now you need to override the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Set a boolean flag to let other parts of you code
// know that the map is ready
isMapReady = true;
// If you need to get info from your marker Implement this
//mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
// #Override
// public boolean onMarkerClick(Marker marker) {
// showMarkerInfo(marker);
// return false;
// }
//});
//If you need a click listener add this
// Add implement the method 'onMapClickLocation'
//mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
// #Override
// public void onMapClick(LatLng latLng) {
// onMapClickLocation(latLng);
// }
//});
// call a function to update your locations
updateMapLocations();
}
Within your(!) protected void onPostExecute(Boolean result) add code to fill the myLocations ArrayList
protected void onPostExecute(Boolean result) {
dialog.dismiss();
myLocations = new ArrayList<LatLng>();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
myLocations.put(lng);
}
// calls the update method when data is available
this.updateMapLocations();
}
and add a call to updateMapLocations() which could look like this:
private void updateMapLocations(){
// update locations won't continue unless the map is ready
if(!isMapReady) return;
// Zoom into your location !! if you need too
// with a destinationLocation of your choice
// perhaps your first location in you ArrayList
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(destinationLocation, zoomFactor));
// PseudoCode!!
// Add your for Loop
// !!! Check to see if your myLocations ArrayList is null before you continue !!!
// !!! or just add another boolean to you onPostExcecute method
// And add the Markers
//Loop Start
//float hue = BitmapDescriptorFactory.HUE_MAGENTA;
//MarkerOptions markerOptions = setMarker(latLng, hue)
// !!! You need to add your destination loop !!!
//mMap.addMarker(markerOptions);
//Loop end!
}
private MarkerOptions setMarker(LatLng latLng, float hue){
MarkerOptions markerOptions = null;
try {
float markerAlpha = 0.7f;
markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue));
markerOptions.position(latLng);
markerOptions.alpha(markerAlpha);
markerOptions.flat(false);
markerOptions.title("What Ever");
markerOptions.snippet("MySnippet");
markerOptions.draggable(false);
markerOptions.zIndex(0.0f);
}
catch (Exception ex){
Log.e(TAG, " setMarker --- " + ex.getMessage());
}
return markerOptions;
}
Notice that updateMapLocations() is called in both your onPostExecute() and the onMapReady() methods. The onPostExecute() might be finished before the onMapReady() is called. So that first when the map is ready the updateMapLocations() will run to completion when data and map are ready.
I wrote this in a text editor - so there will probably be a couple of syntax errors.
Related
i am trying to run a geoquery everytime someone select a place from PlaceAutoComplete fragment and show the markers on the map. It is working fine for the first.When i start the app the icons are are all fine the geoquery is running fine, but when i enter a location second time the app crashes showing an error llegalArgumentException: Unmanaged descriptor below is what i am trying to do.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SupportPlaceAutocompleteFragment autocompleteFragment =
(SupportPlaceAutocompleteFragment)
getChildFragmentManager().findFragmentById
(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new
PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Toast.makeText(getContext(),place.getAddress(),Toast.LENGTH_LONG).show();
Log.i(TAG, "Place: " + place.getName());
Double latitude1 = place.getLatLng().latitude;
Double longitude1 =place.getLatLng().longitude;
LatLng latLng = new LatLng(latitude1,longitude1);
getPeople(latLng); // method to call geofire query
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
return mMainView;
}
public void getPeople(LatLng latLng1){
mMap.clear();
mMap.addCircle(new CircleOptions()
.center(latLng1)
.radius(2000)
.strokeColor(Color.BLACK)
.fillColor(0x220000FF)
.strokeWidth(1)
);
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference().child("Location");
GeoFire geoFire = new GeoFire(ref);
GeoQuery geoQuery = geoFire.queryAtLocation(new
GeoLocation(latLng1.latitude, latLng1.longitude), 2);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(final String key, GeoLocation location) {
UIDLocation.put(key,location);
marker.setIcon(BitmapDescriptorFactory.fromResource
(R.drawable.ic_mapmarker2));
markers.put(key, marker);
for (Map.Entry<String,GeoLocation> entry : UIDLocation.entrySet())
{
final Marker marker = markers.get(entry.getKey());
if (marker != null) {
DatabaseReference mUser =
FirebaseDatabase.getInstance().getReference().child("People")
.child(string);
mUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String display_name =
dataSnapshot.child("name").getValue().toString();
String status =
dataSnapshot.child("status").getValue().toString();
String image =
dataSnapshot.child("image").getValue().toString();
PeopleInfo info = new PeopleInfo();
info.setName(display_name);
info.setStatus(status);
info.setImage(image);
marker.setTag(info);
String iconName = dataSnapshot.child("iconName")
.getValue().toString();
Context context = getContext();
int id = context.getResources().getIdentifier(iconName, "drawable",
context.getPackageName());
String s = String.valueOf(id);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),id);
marker.setIcon(BitmapDescriptorFactory.fromResource(id));
}
#Override
public void onCancelled(DatabaseError
databaseError) {
}
});
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
mUiSettings = mMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(getContext());
Task task= mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new
OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
markeroptn = new MarkerOptions();
markeroptn.position(myPosition);
markeroptn.title("You are Here");
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition,10));
getWorkMen(myPosition);
}
}
});
So far what i have learned from the posts on SO that its because the program is trying to set the icon on marker which is already there. I tried clear() map in the begining of getPeople() but still it is showing the same error.It works fine first time. i also tried remove() also but its also not working.
The problem may come from the way you manage the Marker variables. In the code, you store a marker variable as global outside of the method scope. When calling map.clear(), it makes the marker variable invalid and if somehow you still use this variable to set something, it may cause the exception. The same thing happens with the markers Map you use to map key and Marker, it's not being cleared when map.clear().
Try to manage your map elements more carefully, clear each map element dependently and avoid using map.clear().
Suggestion approach:
Create new marker
private void addMarker(String key, LatLng latLng) {
// Clear the current marker before add the new one
if (marker != null) {
marker.remove();
marker = null;
}
// Store new marker to the variable
marker = mMap.addCircle(new CircleOptions()
.center(latLng)
.radius(2000)
.strokeColor(Color.BLACK)
.fillColor(0x220000FF)
.strokeWidth(1)
);
// Add to markers map if needed
markers.put(key, marker);
}
Clear all markers (clear manually every marker variable available, don't use map.clear:
public synchronized void clear() {
// markers is the marker map
for (Marker marker : markers.values()) {
try {
marker.remove();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
// Clear all the marker map
markers.clear();
// Marker is the your global marker variable
marker.remove();
}
I have a program that wants to direct me to a location review page where the person can read all about the location about that particular location on which he clicks.
I tried implementing it with the code below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places_near_me);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
progressDialog = new ProgressDialog(PlacesNearMeActivity.this);
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(PlacesNearMeActivity.this, ReviewActivity.class);
startActivity(intent);
}
});
} // #EndOfOnCreate!
Markers are displayed on google maps using
public void markPlaces(String result, GoogleMap mMap) {
try {
final JSONObject json = new JSONObject(result);
JSONArray resultArray = json.getJSONArray("results");
for ( int z=0; z<resultArray.length(); ++z ) {
JSONObject locObj = resultArray.getJSONObject(z);
JSONObject geometry = locObj.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
Double lat = Double.parseDouble(location.getString("lat"));
Double lng = Double.parseDouble(location.getString("lng"));
String name = locObj.getString("name");
String placeId = locObj.getString("place_id");
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title(name)
.snippet(placeId));
}
}
catch (JSONException e) { }
} // #EndOfmarkMarkers!
problem is that nothing happens, i tried implementing it using the implements method and onMarkerClickListener as well.. Any solution?
If you use getMapAsync() (and you should!), all map configuration of the map needs to be put into onMapReady(). Until then, you do not have a map to configure. This includes setting listeners for events like info window or marker clicks.
I am able to add multiple markers in my map, but every time I open the application again, added markers are cleared and only one marker at current location is shown. My present code is given below, what changes should I make to get constant location coordinate updates and to save markers so they are present every time I open my map.
public class MainActivity extends FragmentActivity implements View.OnClickListener {
public static final String mapLongitude="longitude";
public static final String mapLatitude="latitude";
FragmentManager fm = getSupportFragmentManager();
Button displayareas;
private GoogleMap newmap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayareas = (Button) findViewById(R.id.display);
displayareas.setOnClickListener(this);
Log.d("Map","MapCreated");
setUpMapIfNeeded();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.display){
Intent intent = new Intent(this, AllAreas.class);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (newmap == null) {
// Try to obtain the map from the SupportMapFragment.
newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (newmap != null) {
setUpMap();
Log.d("MAPS","Map working");
}
else Log.d("MAPS","not working");
}
}
private void setUpMap() {
newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
newmap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
newmap.animateCamera(CameraUpdateFactory.zoomTo(20));
newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location"));
Log.d("LATITUDE",String.valueOf(latitude));
Log.d("LONGITUDE",String.valueOf(longitude));
GoogleMap.OnMarkerClickListener listener = new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
AddGeofenceFragment dFragment = new AddGeofenceFragment();
// Show DialogFragment
dFragment.show(fm, "Dialog Fragment");
return true;
}
};
newmap.setOnMarkerClickListener(listener);
newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Animating to the touched position
newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
newmap.addMarker(markerOptions);
Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));
Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();
}
});
}
}
On constant location update, I recommend using FusedLocationAPI here is the link.
On why the markers were removed. Can you try to remove setUpMapIfNeeded() method in your onResume() ?
My thought is that re-opening the app re initializes the map and all points aren't re-initialized. Honestly I wouldn't think they would stay. It's not the behavior I would expect. If I wanted them to stay I might try to save the points using SQLite. That would save them for sure, but then you need to think about your marker removal user experience.
If you want to show markers when open app in next time.. Please save each lat and long of markers to somewhere (SharedPreference or SQLite ..) and in onCreate() call this data to render in map ..
newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Animating to the touched position
newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
newmap.addMarker(markerOptions);
Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));
//Save it to SharedPreference or SQLite .
Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();
}
});
Currently I have an app that gets the phones GPS location in the background and adds the longitude and latitude coordinates to two separate array lists, I know this part is working fine, however when I do my button click to plot the points to my map it only plots the very first point when I have hundreds in my array list
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0;i<latitude.size();i++)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude.get(i), longitude.get(i))).title("LOCATION " + latitude.get(i) + ", " + longitude.get(i)));
Log.d("LOCATION", latitude.get(i)+ "," + longitude.get(i));
}
Log.d("Count", ""+longitude.size());
}
});
Try this code, I am taking a list of Data class which contains latitude and longitude information which i am setting in Marker options to display on the map. If you want to animate camera you can pass the builder instance to animateCamera and the maps will animate you to all the markers which has been added.
private void insertMarkers(List<Data> list) {
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < list.size(); i++) {
final Lat Lng position = new LatLng(list.get(i).getCurrent_lat(), list.get(i).getCurrent_lng());
final MarkerOptions options = new MarkerOptions().position(position);
mMaps.addMarker(options);
builder.include(position);
}
}
I do it like this to show motors positions on the map with markers of different colors:
private void addMarkersToMap() {
mMap.clear();
for (int i = 0; i < Motors.size(); i++) {
LatLng ll = new LatLng(Motors.get(i).getPos().getLat(), Motors.get(i).getPos().getLon());
BitmapDescriptor bitmapMarker;
switch (Motors.get(i).getState()) {
case 0:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
Log.i(TAG, "RED");
break;
case 1:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
Log.i(TAG, "GREEN");
break;
case 2:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE);
Log.i(TAG, "ORANGE");
break;
default:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
Log.i(TAG, "DEFAULT");
break;
}
mMarkers.add(mMap.addMarker(new MarkerOptions().position(ll).title(Motors.get(i).getName())
.snippet(getStateString(Motors.get(i).getState())).icon(bitmapMarker)));
Log.i(TAG,"Car number "+i+" was added " +mMarkers.get(mMarkers.size()-1).getId());
}
}
}
Motors is an ArrayList of custom objects and mMarkers is an ArrayList of markers.
Note : You can show map in fragment like this:
private GoogleMap mMap;
....
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) {
setUpMap();
}
}
}
private void setUpMap() {
// Hide the zoom controls as the button panel will cover it.
mMap.getUiSettings().setZoomControlsEnabled(false);
// Add lots of markers to the map.
addMarkersToMap();
// Setting an info window adapter allows us to change the both the
// contents and look of the
// info window.
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
// Set listeners for marker events. See the bottom of this class for
// their behavior.
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnMarkerDragListener(this);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
// We check which build version we are using.
#Override
public void onGlobalLayout() {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < mAvailableCars.size(); i++) {
LatLng ll = new LatLng(Cars.get(i).getPos().getLat(), Cars.get(i).getPos().getLon());
bld.include(ll);
}
LatLngBounds bounds = bld.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 70));
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
}
}
And just call setUpMapIfNeeded() in onCreate()
I have a map with a lot of markers. When you click marker, small windows with information will appear. When you click it I want to call fragment. I found that I should use onInfoWindowClick but something is wrong. I can't get any values.
public class Map extends Activity implements OnInfoWindowClickListener{
static final LatLng xxx = new LatLng(70.000, 70,22);
static String[] streets;
static String[] artist;
Coordinate cor = new Coordinate();
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
Resources res = this.getResources();
artist = res.getStringArray(R.array.authors_nicks);
streets = res.getStringArray(R.array.streets);
for (int i = 0; i < cor.coordinatesVale.size(); i++) {
Marker m = googleMap.addMarker(new MarkerOptions()
.position(cor.coordinatesVale.get(i))
.title(artist[i])
.snippet(streets[i])
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker)));
m.getId();
}
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xxx, 12));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onInfoWindowClick(Marker marker) {
String id = marker.getId();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("dsdsd", 3);
startActivity(i);
Log.i("dddd", id); /// CAN't see
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
I found some tutorials, but I'm don't know what I'm doing wrong
In your initializeMap() function, right after you use getMap(), put the following code there. Using this method, you don't need to call implements OnInfoWindowClickListener, but would work the same either way.
if (googleMap != null) {
// More info: https://developers.google.com/maps/documentation/android/infowindows
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Determine what marker is clicked by using the argument passed in
// for example, marker.getTitle() or marker.getSnippet().
// Code here for navigating to fragment activity.
}
});
}
The above code allows you to do something when the user clicks on the info window.
In order to show the info window in the first place, use one either one of the following code snippets, which you have already:
static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400"));
Or,
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne"));
melbourne.showInfoWindow();
Source: Google Maps Android API v2