Map shows multiple markers (overlays) - android

I'm using osmdroid API for maps in my project.
Below is the code I wrote to put an overlay(marker) on selected location.
If I click on map to select any location, it puts an overlay there, but if I tap on map again to select any new location, it shows a new overlay over there (it should) but it doesn't remove the overlay from previous location.
So if I select 10 locations, it shows 10 overlays!
My question is, how to remove previously put overlays when a new location is selected?
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_UP:
Projection proj = mMapView.getProjection();
IGeoPoint loc = proj.fromPixels((int)ev.getX(), (int)ev.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
GeoPoint mypointicon = new GeoPoint(loc.getLatitude(), loc.getLongitude());
final ArrayList<OverlayItem> items=new ArrayList<>();
items.add(new OverlayItem("Here", "Sample Description", mypointicon));
this.mMyLocationOverlay = new ItemizedIconOverlay<>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
return true;
}
#Override
public boolean onItemLongPress(final int index, final OverlayItem item) {
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
mMapView.invalidate();
Toast.makeText(getApplicationContext(),
"Longitude: "+ longitude +" Latitude: "+ latitude , Toast.LENGTH_LONG).show();
}
return super.dispatchTouchEvent(ev);
}

Basically, you have to manage your map overlays.
You could add an overlay: this.mMapView.getOverlays().add(this.mMyLocationOverlay);
So you also can remove it: this.mMapView.getOverlays().remove(index);
And you can remove all of them: this.mMapView.getOverlays().clear();

Related

Changing marker direction to a specific point

I built an android app with a map and I added some custom markers, let me show you.
I want to rotate that picture to points to an another point. I saved the coordinations for the other point too.
This is what is saved by now in the database about this marker.
Latitude and Longitude are the actual marker's position, and del_lat, del_lng is the delivery address which I want to point to. How can I rotate the image in that position?
Here's my ClusterManagerRenderer
public class ClusterManagerRenderer extends DefaultClusterRenderer<FinalMarkerCluster> {
private final IconGenerator iconGenerator;
private ImageView imageView;
private final int markerWidth;
private final int markerHeight;
public ClusterManagerRenderer(Context context, GoogleMap map, ClusterManager<FinalMarkerCluster> clusterManager) {
super(context, map, clusterManager);
iconGenerator = new IconGenerator(context.getApplicationContext());
imageView = new ImageView(context.getApplicationContext());
markerWidth = (int) context.getResources().getDimension(R.dimen.custom_marker_image);
markerHeight = (int) context.getResources().getDimension(R.dimen.custom_marker_image);
imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth,markerHeight));
int padding = (int) context.getResources().getDimension(R.dimen.custom_marker_padding);
imageView.setPadding(padding, padding,padding,padding);
iconGenerator.setContentView(imageView);
}
#Override
protected void onBeforeClusterItemRendered(FinalMarkerCluster item, MarkerOptions markerOptions) {
imageView.setImageResource(item.getIconPicture());
Bitmap icon = iconGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(item.getTitle());
}
#Override
protected boolean shouldRenderAsCluster(Cluster<FinalMarkerCluster> cluster) {
return false;
}
}
And here I'm creating the Marker
private void setRendering(List<MarkerCluster> markerClusters) {
for(int i = 0 ;i < markerClusters.size() ;i++) {
LatLng latLng = new LatLng(markerClusters.get(i).getLatitude(), markerClusters.get(i).getLongitude());
String title = markerClusters.get(i).getTitle();
String snippet = markerClusters.get(i).getSnippet();
LatLng delLatLng = new LatLng(markerClusters.get(i).getDel_lat(), markerClusters.get(i).getDel_lng());
int pic = markerClusters.get(i).getIconPicture();
String offerid = markerClusters.get(i).getOfferid();
FinalMarkerCluster finalMarkerCluster = new FinalMarkerCluster(
latLng,
title,
snippet,
pic,
offerid,
delLatLng
);
finalMarkerClusters.add(finalMarkerCluster);
}
if(mGoogleMap != null) {
if(mClusterManager == null) {
mClusterManager = new ClusterManager<FinalMarkerCluster>(getApplicationContext(),mGoogleMap);
}
if(mClusterManagerRender == null) {
mClusterManagerRender = new ClusterManagerRenderer(getApplicationContext(),mGoogleMap,mClusterManager);
mClusterManager.setRenderer(mClusterManagerRender);
}
for(int j = 0; j< finalMarkerClusters.size();j++) {
mClusterManager.addItem(finalMarkerClusters.get(j));
}
mClusterManager.cluster();
}
}
And here's the MarkerCluster object
public class FinalMarkerCluster implements ClusterItem {
private LatLng position;
private String title;
private String snippet;
private int iconPicture;
private String offerId;
private LatLng deliveryPosition;
public FinalMarkerCluster(LatLng position, String title, String snippet, int iconPicture, String offerId, LatLng deliveryPosition) {
this.position = position;
this.title = title;
this.snippet = snippet;
this.iconPicture = iconPicture;
this.offerId = offerId;
this.deliveryPosition = deliveryPosition;
}
WITH GETTERS AND SETTERS
I just want to rotate the image in that point, Thank you in advance!
This doesn't address clustering but for simple marker rotation two things come in handy:
To determine bearing from point A (the lower-right marker on sample screen) to point B use SphericalUtil.computeHeading:
// add two markers
LatLng m1 = new LatLng(40.763807, -80.362280);
LatLng m2 = new LatLng(40.821666, -80.636242);
MarkerOptions m1o = new MarkerOptions().position(m1).title("m1").flat(true);
MarkerOptions m2o = new MarkerOptions().position(m2).title("m2").flat(true);
double hdg = SphericalUtil.computeHeading(m1,m2);
And to rotate the first marker (A, lower-right) in the direction of the second marker apply the bearing to marker to rotate:
m1o.rotation((float)hdg);
And add markers
mMap.addMarker(m1o);
mMap.addMarker(m2o);
Note the use of flat which maintains north-alignment on screen rotation. If that is not desired then remove the flat for the non-rotated- markers.
Note also the rotation is about the anchor point which may need further consideration.
In this image the screen has been rotated so "screen-up" is ~NNW for demo purposes.

passing data to infowindowclick google maps

I've declared current location latlong and selected location latlong. I want to pass these latlong to onInfoWindowClick().
When I try to use Toast to get the data that I set from marker.setTag(mLatitude) and marker.seTag(mLongitude), It give me the same data only mLongitude. Can anyone help me, please.
This is my code:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
if (parent.getItemAtPosition(position).toString() != "-- Pilih ATM --"){
mMap.clear();
String pilih_atm = (String) parent.getItemAtPosition(position);
// Toast.makeText(getActivity(), pilih_atm, Toast.LENGTH_SHORT).show();
SQLiteDatabase db = dbHelper.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM atm WHERE atm_name = '" + pilih_atm + "'",null);
if (cursor != null){
while (cursor.moveToNext()){
title = cursor.getString(1).toString();
__global_endposition = cursor.getString(2).toString();
String[] exp_endCoordinate = __global_endposition.split(",");
double lat_endposition = Double.parseDouble(exp_endCoordinate[0]);
double lng_endposition = Double.parseDouble(exp_endCoordinate[1]);
LatLng endx = new LatLng(lat_endposition, lng_endposition);
MarkerOptions options = new MarkerOptions();
options.position(endx);
options.title(title);
options.snippet(__global_endposition);
if (title.equals("ATM BNI")){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
}else if(title.equals("ATM BCA")){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
}else if(title.equals("ATM Mandiri")){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
}
Marker marker = mMap.addMarker(options);
marker.setTag(mLatitude);
marker.setTag(mLongitude);
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(getActivity()));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// I want to get current location LatLong and selected location LatLong
// I want execute the LatLong on this method
// this just for testing
Toast.makeText(getActivity(), "LatLng: "+marker.getTag()+", "+marker.getTag(), Toast.LENGTH_SHORT).show();
}
});
}
if (!cursor.isClosed()) {
cursor.close();
cursor = null;
}
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
This is because Marker object has only one Tag object and when you call .setTag() second time, you overrides previously set tag object:
Marker marker = mMap.addMarker(options);
marker.setTag(mLatitude); // tag = mLatitude
marker.setTag(mLongitude); // tag overrides, and now tag = mLongitude
The one of solution is:
Marker marker = mMap.addMarker(options);
marker.setTag("" + mLatitude + "," + mLongitude); // tag now is string: "mLatitude, mLongitude"

android maps displayed multiple markers (LatLng from sqlite)

i use google maps with get (user) device location (GPS Location) in my android app, and insert into database (SQLite) latitude and longitude and adress !
now i want displayed multiple location with LatLng read from database ... no problem in create marker, but in marker info (country, city ...) only show last inserted location for all markers !
this my code :
private void displayMultiplePoint() {
if (LOCATION_TABLE.size() > 0) {
for (int i = 0; LOCATION_TABLE.size() > i; i++) {
int id = LOCATION_TABLE.get(i).getId();
lat = LOCATION_TABLE.get(i).getLatitude();
lng = LOCATION_TABLE.get(i).getLongitude();
place = LOCATION_TABLE.get(i).getPlace();
rate = LOCATION_TABLE.get(i).getRate();
drawMarker(new LatLng(lat, lng), "city", place, rate);
displayToast(id + "" + place);
}
}
}
private void drawMarker(final LatLng point, final String city, final String place, final float rate) {
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
View v = null;
try {
v = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
ImageView map_image = (ImageView) v.findViewById(R.id.maps_image);
map_image.setImageResource(R.drawable.runhd);
TextView city_txt = (TextView) v.findViewById(R.id.maps_city);
city_txt.setText(city);
TextView place_txt = (TextView) v.findViewById(R.id.maps_place);
place_txt.setText(place);
RatingBar rate_bar = (RatingBar) v.findViewById(R.id.exercise_display_rate);
rate_bar.setRating(rate);
} catch (Exception ev) {
System.out.print(ev.getMessage());
}
return v;
}
});
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, 6));
}
i show toast form rowId from lcation table in databse, and displaled 3 row id : 1, 2, 3 but in marker info show last id (id no : 3)
this my fragment :
thank's
I have many solution for your case But at first :
Your fall with setInfoWindowAdapter method it's just invoked one time, So after you iterated your database items and passing info through drawMarker it's just shown the last modified (saved) data from the variables, So i suggest to move it in your for loop (I know it's not a perfect solution) :
for (int i = 0; LOCATION_TABLE.size() > i; i++) {
int id = LOCATION_TABLE.get(i).getId();
lat = LOCATION_TABLE.get(i).getLatitude();
lng = LOCATION_TABLE.get(i).getLongitude();
place = LOCATION_TABLE.get(i).getPlace();
rate = LOCATION_TABLE.get(i).getRate();
drawMarker(new LatLng(lat, lng), "city", place, rate);
displayToast(id + "" + place);
..........
#Override
public View getInfoContents(Marker arg0) {
View v = null;
try {
v = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
ImageView map_image = (ImageView) v.findViewById(R.id.maps_image);
map_image.setImageResource(R.drawable.runhd);
TextView city_txt = (TextView) v.findViewById(R.id.maps_city);
city_txt.setText("city");
TextView place_txt = (TextView) v.findViewById(R.id.maps_place);
place_txt.setText(place);
RatingBar rate_bar = (RatingBar) v.findViewById(R.id.exercise_display_rate);
rate_bar.setRating(rate);
} catch (Exception ev) {
System.out.print(ev.getMessage());
}
return v;
......
}
2nd Solution Using Cursor through your database and use it anywhere (This is will be awesome).
3rd Using Clustering Algorithm in google_maps-utils-example.
The info window is being shown for only last marker because setInfoWindowAdapter() sets info window for the entire map. Inside setInfoWindowAdapter() you need to associate marker argument with corresponding data.
You need to maintain a marker to data map.
Map<Marker, Place> markerToPlaceMap = new HashMap<>();
where, Place is a class to hold city, place, and rating.
class Place {
public String city, place;
public float rating;
}
Note: Please change members to private and implement getters and setters as per your suitability.
Next, Your drawMarker() will change as follows. It needs to add the marker and it's related place to markerToPlace map.
private void drawMarker(final LatLng point, final String city, final String place, final float rate) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
Marker marker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, 6));
markerToPlaceMap.put(marker, new Place(city, place, rating));
}
Finally, you will override GoogleMap.setInfoWindowAdapter() and access Place related to a marker for setting corresponding info contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = null;
try {
v = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
ImageView map_image = (ImageView) v.findViewById(R.id.maps_image);
map_image.setImageResource(R.drawable.runhd);
TextView city_txt = (TextView) v.findViewById(R.id.maps_city);
city_txt.setText(markerToPlace.get(marker).city); // <- Check how corresponding place for a marker is fetched and used
TextView place_txt = (TextView) v.findViewById(R.id.maps_place);
place_txt.setText(markerToPlace.get(marker).place);
RatingBar rate_bar = (RatingBar) v.findViewById(R.id.exercise_display_rate);
rate_bar.setRating(markerToPlace.get(marker).rate);
} catch (Exception ev) {
System.out.print(ev.getMessage());
}
return v;
}
});
i Use Cursor through your database and get data rows (and show in Toast)
but
my code change to this :
private void displayMultiplePoint() {
Cursor cursor = DB_HELPER.LOCATION_MARKERS();
if (cursor.moveToFirst()) {
for (int i = 0; cursor.getCount() > i; i++) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
double lat = cursor.getDouble(cursor.getColumnIndex("latitude"));
double lng = cursor.getDouble(cursor.getColumnIndex("longitude"));
String place = cursor.getString(cursor.getColumnIndex("place"));
float rate = cursor.getFloat(cursor.getColumnIndex("rate"));
displayToast(id + ", " + place + rate);
cursor.moveToNext();
drawMarker(new LatLng(lat, lng));
}
cursor.close();
}
}
i get arg0.getId form : (m0, m1, m2 ...)
public View getInfoContents(Marker arg0)
(is unique for each marker) then select data by id where id = arg0

Add marker to map on tap

I'm coding an application using osmdroid to show a map and i would like to add a marker to it when user taps over map, actually i have been able to do this usin motion event but this adds a marker even when user is zooming in or out the map i don't want this.
This is the code i have to add the marker:
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_DOWN:
Projection proj = myOpenMapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)ev.getX(), (int)ev.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
List<OverlayItem> anotherOverlayItemArray = new ArrayList<OverlayItem>();
ExtendedOverlayItem mapItem = new ExtendedOverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)), this);
mapItem.setMarker(this.getResources().getDrawable(R.drawable.marker));
anotherOverlayItemArray.add(mapItem);
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<OverlayItem>(
this, anotherOverlayItemArray, null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
Toast toast = Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude , Toast.LENGTH_LONG);
toast.show();
}
return super.dispatchTouchEvent(ev);
}
This is how i finally solved it:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
}else{
myOpenMapView.getOverlays().remove(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
}
dlgThread();
return true;
}
};
myOpenMapView.getOverlays().add(touchOverlay);
You should create an Overlay and override the onSingleTapConfirmed() method to get single-taps:
#Override
public boolean onSingleTapConfirmed(final MotionEvent event, final MapView mapView) {
// Handle single-tap here, then return true.
return true;
}

Android, How to remove all markers from Google Map V2?

I have map view in my fragment. I need to refresh map and add different markers based on condition. So, I should remove last markers from map before add new markers.
Actually, some weeks ago app was working fine and suddenly it happened. My code is like this:
private void displayData(final List<Venue> venueList) {
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
.
.
.
}
Last time it was working fine (before new Google Map API announce by Android team in I/O 2013). However, after that I adapted my code to use this new API. Now, I don't know why this method googleMap.clear(); doesn't work!
Any suggestion would be appreciated. Thanks
=======
Update
=======
Complete code:
private void displayData(final List<Venue> venueList) {
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);
// Add marker of user's position
MarkerOptions userIndicator = new MarkerOptions()
.position(new LatLng(lat, lng))
.title("You are here")
.snippet("lat:" + lat + ", lng:" + lng);
googleMap.addMarker(userIndicator);
// Add marker of venue if there is any
if(venueList != null) {
for(int i=0; i < venueList.size(); i++) {
Venue venue = venueList.get(i);
String guys = venue.getMaleCount();
String girls= venue.getFemaleCount();
String checkinStatus = venue.getCan_checkin();
if(checkinStatus.equalsIgnoreCase("true"))
checkinStatus = "Checked In - ";
else
checkinStatus = "";
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
.title(venue.getName())
.snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));
googleMap.addMarker(markerOptions);
}
}
// Move the camera instantly to where lat and lng shows.
if(lat != 0 && lng != 0)
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String str = marker.getId();
Log.i(TAG, "Marker id: " + str);
str = str.substring(1);
int markerId = Integer.parseInt(str);
markerId -= 1; // Because first item id of marker is 1 while list starts at 0
Log.i(TAG, "Marker id " + markerId + " clicked.");
// Ignore if User's marker clicked
if(markerId < 0)
return;
try {
Venue venue = venueList.get(markerId);
if(venue.getCan_checkin().equalsIgnoreCase("true")) {
Fragment fragment = VenueFragment.newInstance(venue);
if(fragment != null)
changeFragmentLister.OnReplaceFragment(fragment);
else
Log.e(TAG, "Error! venue shouldn't be null");
}
} catch(NumberFormatException e) {
e.printStackTrace();
} catch(IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
});
Okay finally I found a replacement way to solve my problem. The interesting problem is when you assign a marker to map, it's id is 'm0'. When you remove it from map and assign new marker you expect the id should be 'm0' but it's 'm1'. Therefore, it showed me the id is not trustable. So I defined List<Marker> markerList = new ArrayList<Marker>(); somewhere in onActivityCreated() of my fragment.
Then changed above code with following one. hope it helps others if they have similar issue with markers.
private void displayData(final List<Venue> venueList) {
Marker marker;
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
markerList.clear();
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);
// Add marker of user's position
MarkerOptions userIndicator = new MarkerOptions()
.position(new LatLng(lat, lng))
.title("You are here")
.snippet("lat:" + lat + ", lng:" + lng);
marker = googleMap.addMarker(userIndicator);
// Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
markerList.add(marker);
// Add marker of venue if there is any
if(venueList != null) {
for (Venue venue : venueList) {
String guys = venue.getMaleCount();
String girls = venue.getFemaleCount();
String checkinStatus = venue.getCan_checkin();
if (checkinStatus.equalsIgnoreCase("true"))
checkinStatus = "Checked In - ";
else
checkinStatus = "";
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
.title(venue.getName())
.snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));
marker = googleMap.addMarker(markerOptions);
// Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
markerList.add(marker);
}
}
// Move the camera instantly to where lat and lng shows.
if(lat != 0 && lng != 0)
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
int markerId = -1;
String str = marker.getId();
Log.i(TAG, "Marker id: " + str);
for(int i=0; i<markerList.size(); i++) {
markerId = i;
Marker m = markerList.get(i);
if(m.getId().equals(marker.getId()))
break;
}
markerId -= 1; // Because first item of markerList is user's marker
Log.i(TAG, "Marker id " + markerId + " clicked.");
// Ignore if User's marker clicked
if(markerId < 0)
return;
try {
Venue venue = venueList.get(markerId);
if(venue.getCan_checkin().equalsIgnoreCase("true")) {
Fragment fragment = VenueFragment.newInstance(venue);
if(fragment != null)
changeFragmentLister.OnReplaceFragment(fragment);
else
Log.e(TAG, "Error! venue shouldn't be null");
}
} catch(NumberFormatException e) {
e.printStackTrace();
} catch(IndexOutOfBoundsException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
}
If you want to clear "all markers, overlays, and polylines from the map", use clear() on your GoogleMap.
Use map.clear() to remove all markers from Google map
Suppose there is an ArrayList of 2 locations. Now, you display markers on the map based on that array. There will be two markers. When you click on the first marker it gives you a marker index m0 and the second is m1.
Say that you refresh location array and now you got an array with 3 locations. You got 3 markers. But when you click on the first one, it gives you marker index m2 (as if it continues counting from the first location arraw) the second is m3 and the third is m4. What you actually want is to make it as m0, m1, m2.
Now, when you build you location array you probably call location.add("you location")... and when you rebuild it (refresh it) you call location.clear() first and then build it again.
SOLUTION:
First, make another dummy array similar to location array and build it in for loop together with a real location array: locaionDummy.add(i) but don't you EVER refresh it - that way it keeps building and you will know how many locations you've ever had from the very beginning.
Second, do something like this (example of setting image) with mIndex as int variable:
void locatePins() {
mIndex = locationDummy.size()-location.size();
for (int i = 0; i < userID.size(); i++) {
LatLng pgLocation = new LatLng(Double.parseDouble(latArr.get(i)), Double.parseDouble(lngArr.get(i)));
myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.map_marker_info, null);
RelativeLayout markerInfo= view.findViewById(R.id.markerInfo);
TextView name = view.findViewById(R.id.userName);
TextView details = view.findViewById(R.id.userInfo);
ImageView img = view.findViewById(R.id.userImg);
name.setText(marker.getTitle());
details.setText(marker.getSnippet());
img.setImageBitmap (bmImg.get(Integer.parseInt(marker.getId().replaceAll("[^\\d.]", ""))-mIndex));
return view;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
// ... the rest of the code
}
}
The key is to subtract the real location.size() from a locationDummy.size() to get a number int mIndex that you will subtract later on from marker.getId()
If you need to remove only the markers, and leave other things such as ground overlay,etc there, use:
marker.remove();
or if you have many:
if(markers!=null&&mMap!=null){
for(int i=0;i<markers.size();i++){
markers.get(i).remove();
}
}
where
List<Marker> markers = new ArrayList<>();

Categories

Resources