onMarkerClick using switch Case - java

I want to make marker Application using Google Maps but . I Have problem about onMarkerClick using switch Case, Iam using array to add Marker to My Application and when marker OnCLick he can call different Activity for each marker .I Have problom about that.. How I can using onMarkerClick with switch case for my application..??? Please Help . Here is My Code :
public static final String TAG = markerbanyak.TAG;
final LatLng CENTER = new LatLng(43.661049, -79.400917);
class Data {
public Data(float lng, float lat, String title, String snippet, String icon) {
super();
this.lat = (float)lat;
this.lng = (float)lng;
this.title = title;
this.snippet = snippet;
this.icon = icon;
}
float lat;
float lng;
String title;
String snippet;
String icon;
}
Data[] data = {
new Data(-79.400917f,43.661049f, "New New College Res",
"Residence building (new concrete high-rise)", "R.drawable.mr_kun"),
new Data(-79.394524f,43.655796f, "Baldwin Street",
"Here be many good restaurants!", "R.drawable.mr_kun"),
new Data(-79.402206f,43.657688f, "College St",
"Lots of discount computer stores if you forgot a cable or need to buy hardware.", "R.drawable.mr_kun"),
new Data(-79.390381f,43.659878f, "Queens Park Subway",
"Quickest way to the north-south (Yonge-University-Spadina) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.403732f,43.666801f, "Spadina Subway",
"Quickest way to the east-west (Bloor-Danforth) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.399696f,43.667873f, "St George Subway back door",
"Token-only admittance, else use Spadina or Bedford entrances!", "R.drawable.mr_kun"),
new Data(-79.384163f,43.655083f, "Eaton Centre (megamall)",
"One of the largest indoor shopping centres in eastern Canada. Runs from Dundas to Queen.", "R.drawable.mr_kun"),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.peta);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
mMap = supportMapFragment.getMap();
Marker kuningan = mMap.addMarker(new MarkerOptions()
.position(KUNINGAN)
.title("Kuningan")
.snippet("Kuningan ASRI")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mr_kun)));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KUNINGAN, 2));
// Zoom in, animating the camera.
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
public void wisata(){
if (mMap==null) {
Log.d(TAG, "Map Fragment Not Found or no Map in it!!");
return;
}
for (Data d : data) {
LatLng location = new LatLng(d.lat, d.lng);
Marker wisata =mMap.addMarker(new MarkerOptions()
.position(location)
.title(d.title)
.snippet(d.snippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mr_wis)));
// Let the user see indoor maps where available.
mMap.setIndoorEnabled(true);
// Enable my-location stuff
mMap.setMyLocationEnabled(true);
// Move the "camera" (view position) to our center point.
mMap.moveCamera(CameraUpdateFactory.newLatLng(CENTER));
// Then animate the markers while the map is drawing,
// since you can't combine motion and zoom setting!
final int zoom = 14;
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000, null);
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
return false;
}
});
}
}

#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
if(v.getTitle().contains("New New College Res")){
// do if marker has this title
}else if(v.getTitle().contains("Baldwin Street")){
// do if marker has this title
} // and so on
return false;
}
});

Marker class if final so you can't extend it and add your own attributes. You will have to handle this using your own logic.
You can do this in two ways.
You already have a Data list with all marker data.
1) You could try to set "snippet" attribute of Marker with your array index of Data array and on onMarkerClick you can get Snippet change it back to int and that would be your Data Array's index. So you can get that your clicked Marker and it's Data object and do whatever you want to do.
2) Use HashMap.
It will look something like this
HashMap<Marker, Integer> hashMap = new HashMap<Marker, Integer>();
// now even in your loop where you are adding markers. you can also add that marker to this hashmap with the id of Data array's index.
hashMap.add(marker, indexOfDataArray);
// final in your onMarkerClick, you can just pass marker to hashMap and get indexOfDataArray and base of that do whatever you want to do.
int id = hashMap.get(marker);

Related

Why does my for loop not make each marker unique in my google maps activity

I am trying to open a new activity when a user clicks on the window of a marker.
Now I am doing everything correctly it seems and it even works but only for one single shop, it brings all the information from that single shop and places it in every marker every time a user clicks it.
I am wondering why this is happening and why is my shop object not being unique to each marker since its inside of a for loop.
When I open any window from any marker it takes me to the same shop details which in my case is "Starbucks". Why is that?
Here is the code:
public void onMapReady(final GoogleMap googleMap) {
CollectionReference mapRef = fStore.collection("Shops");
Query mapQuery = mapRef;
mapRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(final QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots){
final Shop shop = documentSnapshot.toObject(Shop.class);
String Lat = shop.getLatitude();
String Long = shop.getLongitude();
float latitude = Float.parseFloat(Lat);
float longitude = Float.parseFloat(Long);
final LatLng shopLoc = new LatLng(latitude, longitude);
final Marker markers = googleMap.addMarker(new MarkerOptions()
.position(shopLoc)
.title(""+shop.getName())
.snippet(shop.getShopPID()));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent i = new Intent(MapActivity.this,DetailsActivity.class);
i.putExtra("shopModel",shop);
startActivity(i);
}
});
}
}
});
}
i solved it!!!
i did some research and there were other stackoverflow answers to this question. i just took out the oninfoclick outside the for loop and did as follows:
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(shopLoc)
.title(""+shop.getName()).snippet("Click to view shops information"));
marker.setTag(shop);
and then outside the for loop i did this:
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent i = new Intent(MapActivity.this,DetailsActivity.class);
Shop shop2 = (Shop) marker.getTag();
i.putExtra("shopModel",shop2);
startActivity(i);
}
});

How to include ID in marker in addition to title and snippet

when addMarker in map android studio, i can only be input title and snippet.
How to add other parameters such as id?
Which I can later get when clicking on the marker.
private void addMarker(LatLng latlng, final String title, final String deskripsi, final String id) {
markerOptions.position(latlng);
markerOptions.title(title);
markerOptions.snippet(deskripsi);
gMap.addMarker(markerOptions);
gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getApplicationContext(), marker.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
Use one Hashmap for storing marker and ids
private HashMap<Marker, Integer> markerIdMapping = new HashMap<>();
private void addMarker(LatLng latlng, final String title, final String deskripsi, final String id) {
markerOptions.position(latlng);
markerOptions.title(title);
markerOptions.snippet(deskripsi);
Marker marker = gMap.addMarker(markerOptions);
markerIdMapping.put(marker, id);
gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getApplicationContext(), marker.getTitle(), Toast.LENGTH_SHORT).show();
String markerId = markerIdMapping.get(marker);
}
});
}
You can use #marker.setTag
Ex :
Marker marker = mMap.addMarker(markerOptions);
marker.setTag([You can give here]); // marker.setTag(30)
Later you can get using getTag
int id = (int) marker.getTag();
How to add other parameters such as id?
What other fields do you want to be set apart from the marker id?
Marker id is autogenerated when we create a marker using GoogleMap.addMarker. What you can do is after the marker is created, use a HashMap to map all marker id's and inside getInfoWindow(Marker marker) or getInfoContents(Marker marker) use the marker.getId() to proceed.
To uniquely identify your marker, use :
setTag(Object obj)
and to retrieve, use:
getTag()
see the answer posted here:
How to set tag to Google Map's marker in Android?

how to get direction to the shortest path outside circle in google maps android, when my current location is inside 2 or more circles?

How to get direction to the nearest location outside circle if the blue dots is the current location?
1[1
and how to display markers ONLY around the current location in radius 2000m? I have stored the mapping lanslide in database and it displays when the app launch and it needs 7-9 seconds to load these markers. now i need to display only around the current location in order the app going smooth.
[these are the mapping dots of lanslide]
im doing my final projet, and I have a fEature which is really difficult.
Im on my android project, making a warning application on android about lanslide disaster, I do the mapping dots of lanslide locations and collect about 150 couples of lattitudes and longitudes and put it on database.
I assume if the user inside a circle, they are in lanslide location and they are not safe
the red zone radius is 2KM from the center of circle.
the orange zone radius is 1km from the center of circle.
the yellow zone radius is 500m from the center of circle
when the app is launch, the map will show up and animate the camera to my current location.
and then the app will tell the user if they are safe or not.
if the user OUTSIDE THE CIRCLE, then the user is safe. but,
if the current location inside the circle, then the user is not safe.
WHEN THE USER IS NOT SAFE, THE APP will give direction to shortest path outside the circle.
My app is almost done, except the last feature, I'm out of idea how to figure it out,
HOW THE APP CAN GIVE THE DIRECTION TO THE SHORTEST PATH OUTSIDE A CIRCLE??
unfortunately, how can the app will get direction to the shorthest outside circle for user if the CURRENT LOCATION inside 3 or mores circle ? and what google's libarry i can use for solve this?
how to get direction outside many circles? please help me.
enter image description here
this is my code:
public class MenuMaps extends Fragment implements OnMapReadyCallback {
private static MenuMaps instance = null;
private SupportMapFragment sMapFragment;
private MapView mMapView;
SupportMapFragment mapFragment;
private GoogleMap mMap;
private String[] id, desa, status_des;
boolean markerD[];
private Double latitude, longitude;
private Circle mCircle;
private Marker mMarker;
LatLng lokasisekarang;
boolean mapReady = false;
private GoogleApiClient client;
private GoogleApiClient client2;
public static MenuMaps getInstance() {
if (instance == null) {
instance = new MenuMaps();
Log.d( "MenuMaps", "getInstance");
}
return instance;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
Log.d("MenuMaps", "OnCreateView");
View inflatedView = inflater.inflate(R.layout.menu_maps, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
Button btnMap = (Button) inflatedView.findViewById(R.id.btnMap);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mapReady)
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}) ;
Button btnSatellite = (Button) inflatedView.findViewById(R.id.btnSatellite);
btnSatellite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mapReady)
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
});
Button btnHybrid = (Button) inflatedView.findViewById(R.id.btnHybrid);
btnHybrid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mapReady)
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
return inflatedView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu Maps");
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void getLokasi() {
Log.d("desaStatus", "getLokasi");
String url = "http://dharuelfshop.com/skripsi/desaStatus.php/";
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("desaStatus", response);
Gson gson = new Gson();
try {
JSONObject objinduk = new JSONObject(response);
List<DesaStatus> listDesaStatus = gson.fromJson(objinduk.getString("desaStatus"), new TypeToken<List<DesaStatus>>() {
}.getType());
Circle circleTerdekat = null;
Float distanceTerdekat = null;
for (DesaStatus desaStatus : listDesaStatus
) {
Log.d("desaStatus", desaStatus.toString());
LatLng center = new LatLng(desaStatus.lat_bcn,
desaStatus.long_bcn);
MarkerOptions markerOptions = new MarkerOptions()
.position(center)
.title("Desa : " + desaStatus.nama_des)
.snippet("Status : " + desaStatus.jenis_status)
.icon(BitmapDescriptorFactory
.defaultMarker(desaStatus.kode_warna));
mMarker = mMap.addMarker(markerOptions);
CircleOptions CircleOptions = new CircleOptions()
.center(center)
.radius(desaStatus.radius)//in meters
.strokeColor(Color.parseColor(desaStatus.warna_radius))
.strokeWidth(2)
.fillColor(Color.parseColor(desaStatus.warna_radius));
mCircle = mMap.addCircle(CircleOptions);
//hitung distance dan Status circle
float[] distance = new float[2];
Location.distanceBetween( lokasisekarang.latitude, lokasisekarang.longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if (circleTerdekat == null) {
circleTerdekat = mCircle;
distanceTerdekat = distance[0];
} else {
if (distance[0] < distanceTerdekat ) {
distanceTerdekat = distance[0];
circleTerdekat = mCircle;
}
}
}
Log.d("circleTerdekat", "center: " + circleTerdekat.getCenter().latitude + " " + circleTerdekat.getCenter().longitude );
if( distanceTerdekat > circleTerdekat.getRadius() ){
Toast.makeText(getContext(), "You are safe, distance from center: " + distanceTerdekat + " radius: " + circleTerdekat.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "You are not safe, distance from center: " + distanceTerdekat + " radius: " + circleTerdekat.getRadius() , Toast.LENGTH_LONG).show();
}
} catch (JSONException error) {
Log.d("desaStatusError", error.toString());
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Error woy");
//Message
builder.setMessage("Error " + error); //+ error diganti sama (VolleyError error)
//Message
//builder.setIcon()
builder.setPositiveButton("Refreshh", new DialogInterface.OnClickListener() {
#Override //O nya huruf gede
public void onClick(DialogInterface dialog, int which) {
getLokasi();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
// menambah request ke request queue
VolleyRequest.getInstance().addToRequestQueue(request);
}
public void getCurrentLocation() {
GpsTracker gps = new GpsTracker(getActivity());
if (gps.canGetLocation()) { // gps enabled
//Getting longitude and latitude
latitude = gps.getLatitude();
longitude = gps.getLongitude();
lokasisekarang = new LatLng(latitude, longitude);
drawMarkerWithCircle(lokasisekarang);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lokasisekarang, 14f));
// \n is for new line
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
//gps.stopUsingGPS();
}
}
private void drawMarkerWithCircle(LatLng lokasisekarang) {
MarkerOptions markerOptions = new MarkerOptions()
.position(lokasisekarang)
.title("You are here")
.snippet("here")
.icon(BitmapDescriptorFactory
.defaultMarker(HUE_BLUE));
mMarker = mMap.addMarker(markerOptions);
CircleOptions circleOptions = new CircleOptions()
.center(lokasisekarang)
.radius(2000)
.strokeWidth(2)
.strokeColor(Color.BLUE)
.fillColor(Color.parseColor("#500084d3"));
mMap.addCircle(circleOptions);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mapReady = true;
mMap = googleMap;
getCurrentLocation();
getLokasi();
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.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(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true); // buat enable button location
}}
In order to show directions you need 2 points the origin and destination. The origin in this case will be your user's location.
Finding the destination point:
1) Currently you are storing the centre of these circular zones and their radii (500m, 1km etc). In addition to these you can easily calculate for each circle 4 'safe' points that lie along 4 directions (say N,S,E,W) and store them.
2) These points divide your circle into 4 quadrants. Now all you need to do is find which quadrant of the circle the user's current location is in and compare the distance between the points forming the quadrant and choose the lower of the two as your destination.
3) Use the Google Maps Directions API to show directions .
If you want to increase the accuracy of the algorithm all you need to do is increase the number of directions which will effectively divide your circle into more smaller parts and the destination will be more optimal.
Here '4' was just an arbitrary number . You can have different number based on number of safe points you choose and that will determine the accuracy of the algorithm
EDIT: Handling multiple circles intersecting is also easy. All you need to do then is instead of calculating the shortest for 1 circle you calculate for all the circles where the point lies and then find the min distance
Algorithm:
1) For each circle choose 'n' safe points. These 'n' points will form n - 1 sectors in the circle.
2) Get the current location of the user ( say A) and find all the circles where this point is included.
3) For each circle where pt A lies, calculate sector in which it lies. Say it lies on sector formed by points X_i and Y_i. Calculate the distance AX_i and AY_i.
4) Choose the minimum across all distances AX_i, AY_i and show navigation instructions for those points
It doesn't matter if the markers appear visually close to each other.. You're not going to visually find the direction the computing device is going to do it. Lat/Long values have a very high order of precision anyway.

Send argument to fragment in a listener in a loop

Hey Stackoverflow community,
I am working on an android app for an academic project, the goal is to retrieve data using an API and display it on a map using markers.
I would like to display some details in a fragment when the user click on the marker. I use beginTransaction and setArguments to do so and it works for one markers.
My problem is that my markers are created in a for loop and I can only retrieve the arguments from the last iteration of the loop.
Here is the loop in my mainActivity:
JSONObject jsonObject = new JSONObject(res);
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++ ) {
String name = placeList.get(i).getName();
double lat = placeList.get(i).getLat();
double lng = placeList.get(i).getLng();
map.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title());
// CustomOnMarkerClickListener(place) implements GoogleMap.OnMarkerClickListener
map.setOnMarkerClickListener(new CustomOnMarkerClickListener(place));
}
Here is my custom OnMarkerClickListener
public class CustomOnMarkerClickListener implements GoogleMap.OnMarkerClickListener {
JSONObject place;
public CustomOnMarkerClickListener(JSONObject place) {
this.place = place;
}
#Override
public boolean onMarkerClick(Marker marker) {
InfoPanelActivity ipa = new InfoPanelActivity();
FragmentManager fm = getSupportFragmentManager();
Bundle args = new Bundle();
args.putString("place", place.toString());
ipa.setArguments(args);
if(findViewById(R.id.textView2) == null) {
fm.beginTransaction()
.add(R.id.info_panel_frame, ipa)
.commit();
} else {
fm.beginTransaction()
.replace(R.id.info_panel_frame, ipa)
.commit();
}
return false;
}
}
And here is how I get the argument in my fragment
Bundle args = getArguments();
String name = args.getString("place");
TextView tv = (TextView) getView().findViewById(R.id.textView2);
tv.setText("test: " + name);
I had really appreciate if you could help, I really don't see how to solve that problem.
Thanks
When you call
map.setOnMarkerClickListener(new CustomOnMarkerClickListener(place));
You are re-setting the click listener, not adding another one. The click listener is on the map itself, not individual marker. At the end of the for loop, the click listener will have the data of "place" for only the last marker. You need to save the place data inside of each Marker and access it in your onMarkerClick() method.
Something like...
for (int i = 0; i < results.length(); i++ ) {
String name = placeList.get(i).getName();
double lat = placeList.get(i).getLat();
double lng = placeList.get(i).getLng();
map.addMarker(new CustomMarkerOptions()
.position(new LatLng(lat, lng))
.place(place)
.title());
}
// CustomOnMarkerClickListener(place) implements GoogleMap.OnMarkerClickListener
map.setOnMarkerClickListener(new CustomOnMarkerClickListener());
Then in your click listener class..
#Override
public boolean onMarkerClick(Marker marker) {
String place = marker.place();
...
}

Android Google maps adding multiple markers, cannot bind onInfoWindowClick method

I am currently trying to add multiple markers to my Android application. This works just perfectly. The only thing I am getting stuck at is the fact that I cannot bind multiple "onInfoWindowClick" on multiple markers.
For instance, if I have like:
for (int i = 0; i < randomList; i++) {
MarkerOptions marker = new MarkerOptions().position(latlng).title(MainActivity.list.get(i).aMessage);
// adding marker
googleMap.addMarker(marker);
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Do something onclick
}
});
}
This would result in a infowindowclick that works, for each marker, but I always get the same data back inside that "// Do something onclick", this is because the last marker is getting set to this event.
What is my procedure to attach this event to multiple markers?
Create a new Marker on every loop and execute the method: showInfoWindow();
for (int i = 0; i < randomList; i++) {
// MarkerOptions marker = new MarkerOptions().position(latlng).title(MainActivity.list.get(i).aMessage);
// adding marker
// googleMap.addMarker(marker);
googleMap.addMarker(new MarkerOptions().position(latlng).title(MainActivity.list.get(i).aMessage)).showInfoWindow();
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Do something onclick
}
});
}
by the way you are setting the same latlng value!
You should not be calling setOnInfoWindowClickListener() inside a loop, this just needs to be called once, and it will apply to all Markers.
The Marker object that gets passed into onInfoWindowClick(Marker marker) will always be the Marker that was just clicked.
So, take that out of the loop. Next, in order to figure out what Marker was just clicked, you could get the title of the Marker, and loop through your list until you find the list item that has a aMessage value that corresponds to the Marker's title.
Note you could also identify that current marker by location by calling marker.getPosition();.
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
//get location of Marker that was just clicked
LatLng latLon = marker.getPosition();
// get the title of Marker that was just clicked
String title = marker.getTitle();
//find item in the list that corresponds to currently clicked Marker
for (int i = 0; i < MainActivity.this.list.size(); i++){
if (title.equals(MainActivity.this.list.get(i).aMessage)){
//found current list item corresponding to
//the Marker that was just clicked!
}
}
}
});
for (int i = 0; i < randomList; i++) {
MarkerOptions marker = new MarkerOptions().position(latlng).title(MainActivity.this.list.get(i).aMessage);
// adding marker
googleMap.addMarker(marker);
}
I answered a similar question here, you may find that helpful as well.

Categories

Resources