Removing Markers in android - android

I have a Global array Object like Marker marker_array[]; and later in Layout click I initialized it as marker_array = new Marker[8];. I want to add markers to map on that layout and remove on 2nd click so I created clickcount Global variable with zero value.
My proper code is here
final RelativeLayout layout = (RelativeLayout) findViewById(R.id.track_div);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickcount++;
point_new = new LatLng[8];
point_new[0] = new LatLng(31.5301843, 74.3207487);
point_new[1] = new LatLng(31.5214693,74.3236027);
point_new[2] = new LatLng(31.5194393, 74.3257327);
point_new[3] = new LatLng(31.4942166, 74.3004533);
point_new[4] = new LatLng(31.4864646, 74.2911203);
point_new[5] = new LatLng(31.4803596, 74.2787933);
point_new[6] = new LatLng(31.4764716, 74.2638203);
point_new[7] = new LatLng(31.4775236, 74.2628873);
// initialize marker_array;
marker_array = new Marker[8];
Toast.makeText(getApplicationContext(), "count "+clickcount, Toast.LENGTH_SHORT).show();
//
if (clickcount % 2 == 0) {
polyline.setVisible(false);
for (int i = 0; i < point_new.length; i++){
Toast.makeText(getApplicationContext(), "marker length ="+marker_array.length, Toast.LENGTH_SHORT).show();
marker_array[i].remove();
// marker_array.setVisible(false);
}
} else {
polyline.setVisible(true);
for (int i = 0; i < point_new.length; i++) {
// marker_array = new Marker[point_new.length];
MarkerOptions markerOptions = new MarkerOptions()
.position(point_new[i]);
marker_array[i] = mMap.addMarker(markerOptions);
marker_array[i].setTitle("Points");
marker_array[i].setSnippet("Distance = 9.6 km, Time = 20 minute/s");
marker_array[i].setIcon(BitmapDescriptorFactory.fromResource(R.drawable.bus));
}
}
The problem is that it creates all 8 markers But does not remove, Even if in if condition where I'm trying to remove markers Toast shows proper length 8. Butt when I remove any of the marker_array separately as marker_array[7] it removes it.
How can I remove all the markers in marker_array without map.clear(); method because I have some other things like polyline etc that I do not want to remove.
Any effort will be appreciated.

Use this to add markers
As Global
List<Marker> mMarkers = new ArrayList<Marker>();
And In your for loop add markers to this list like
for (int i = 0; i < point_new.length; i++) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point_new[i]);
Marker marker = mMap.addMarker(markerOptions);
marker.setTitle("Point");
marker.setSnippet("this is snippet");
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.p));
mMarkers.add(marker); // <-- Like this
}
And to remove markers
private void removeMarkers() {
for (Marker marker: mMarkers) {
marker.remove();
}
mMarkers.clear();
}
hope it will help.

Try this,
private ArrayList<Marker> mMarkers;
...
private void removeMarkers() {
for (Marker marker: mMarkers) {
marker.remove();
}
mMarkers.clear();
}

The method signature for addMarker is:
public final Marker addMarker (MarkerOptions options)
So when you add a marker to a GoogleMap by specifying the options for the marker, you should save the Marker object that is returned (instead of the MarkerOptions object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove() to remove it from the map.
As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean).
Similar to Remove a marker from a GoogleMap

marker.setVisible(false) worked flawlessly for me for hidding the markers, and I have returned all of them with the marker.setVisible(true). The .clear() was slowing my app a lot. I do not recomend it.

Related

Google Place - set On Info Window Click Listener

How I can setOnInfoWindowClickListener if have this loop?
I'm trying to create an Android application. To retrieve data from json file I use retrofit.
I need help when clicking on the info window I want to show more information about the clicked place.
I want to display Toast with the name of clicked the Nearby Places.
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
final String placeName = response.body().getResults().get(i).getName();
// String vicinity = response.body().getResults().get(i).getVicinity();
// Double ratting = response.body().getResults().get(i).getRating();
final List <String> nameLocation = new ArrayList<>();
nameLocation.add(placeName);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(markerColor));
// Adding Marker to the Camera.
Marker mMarker = mMap.addMarker(markerOptions);
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
As you mentioned in the comments, you can show a toast in when a marker on your map is clicked by doing the following.
First attach a marker click listener to your map:
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
//TODO: Show your toast
}
});
Next within the click handler, create a new toast. Make sure you have the application context within this handler, so that you can attach the toast to that context.
final Context context = this;
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
Toast toast = Toast.makeText(context, marker.getTitle(), "Additional info", Toast.LENGTH_SHORT);
toast.show();
}
});

My polylines wont disappear when I click the button the 2nd time

What I want to happen is when I type something in the AutoCompleteTextView according to the if condition and when I click the button FOR THE FIRST TIME the program will do what I ask correctly.
("correctly" meaning: read what's in the AutoCompleteTextView and does the 'IF' condition correctly);
But when I click the button the second time changing what I typed in the AutoCompleteTextView to another 'IF' condition, the marker and the polyline that the program did in passing the first 'if' condition won't disappear (Does not get removed); this happens infinitely number of times of button click, only the first button click is correctly done/read by the program.
My onMapReady Codes:
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
//Position of Manila
LatLng manila = new LatLng(14.5995, 120.9842);
//adding details in Marker
MarkerOptions option = new MarkerOptions();
option.position(manila).title("Manila");
//adding marker in map
map.addMarker(option);
map.moveCamera(CameraUpdateFactory.newLatLng(manila));
//gotoLocation line
gotoLocationZoom(14.5995, 120.9842, 15);
//end gotoLocation line
//routes
apple();
banana();
cherry();
//markerclick
map.setOnMarkerClickListener(this);
}
My onMarkerClick codes: (But I think it's irrelevant because I don't do clicking but I think you might need the whole code as much as possible)
#Override
public boolean onMarkerClick(Marker marker) {
tag = marker.getTag().toString();
return false;
}
This is my onButtonClick codes:
public void onClick(View view){
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.text_category);
if (textView.getText().toString().equals("apple")){
Toast.makeText(this, "This is my message", Toast.LENGTH_LONG).show();
//remove Lines
banana_line.remove();
cherry_line.remove();
//Remove Markers
banana_marker.remove();
cherry_marker.remove();
//Show Apple Marker and lines
apple();
} else if (textView.getText().toString().equals("banana")){
Toast.makeText(this, "This is my message", Toast.LENGTH_LONG).show();
//Remove Lines
apple_line.remove();
cherry_line.remove();
//Remove markers
apple_marker.remove();
cherry_marker.remove();
//Show banana Marker and lines
banana();
}else if (textView.getText().toString().equals("cherry")){
Toast.makeText(this, "This is my message", Toast.LENGTH_LONG).show();
//Remove Lines
apple_line.remove();
banana_line.remove();
//Remove Markers
apple_Marker.remove();
banana_Marker.remove();
//Add cherry Marker and Lines
cherry();
} else{
Toast.makeText(this, "Error no fruit like that", Toast.LENGTH_LONG).show();
}
This is my sample polylines and Markers codes:
public void apple() {
LatLng apple = new LatLng(14.617071, 120.989945);
//All about the Marker
MarkerOptions appleMarkerOptions = new MarkerOptions();
appleMarkerOptions.position(apple);
appleMarkerOptions.title("Apple");
appleMarkerOptions.snippet("So yummy");
apple_marker = map.addMarker(appleMarkerOptions );
apple_marker.setTag("Apple");
//The Polylines
apple_line= map.addPolyline(new PolylineOptions().add(
new LatLng(14.617071, 120.989945),
new LatLng(14.605693, 121.000863),
new LatLng(14.605599, 121.000939),
new LatLng(14.603097, 121.001786),
new LatLng(14.602900, 121.001089),
new LatLng(14.605246, 121.000252),
new LatLng(14.613429, 120.992410),
new LatLng(14.611934, 120.990768),
new LatLng(14.617094, 120.985795)
)
.width(5)
.color(Color.RED)
);
public void banana(){
LatLng banana = new LatLng(14.612056, 120.995471);
//All about the Marker
MarkerOptions bananaMarkerOptions = new MarkerOptions();
bananaMarkerOptions .position(banana);
bananaMarkerOptions .title("Banana");
bananaMarkerOptions .snippet("I'm so yellow");
banana_marker = map.addMarker(bananaMarkerOptions );
banana_marker.setTag("Banana");
//The Polylines
banana_line = map.addPolyline(new PolylineOptions().add(
new LatLng(14.611319, 120.994752),
new LatLng(14.612855, 120.996404)
)
.width(5)
.color(Color.YELLOW)
);
}
public void cherry(){
//All about the Marker
LatLng cherry = new LatLng(14.612056, 120.995471);
MarkerOptions cherryMarkerOptions = new MarkerOptions();
cherryMarkerOptions.position(cherry);
cherryMarkerOptions.title("Cherry");
cherryMarkerOptions.snippet("Cherry delight");
//The Polylines
cherry_marker= map.addMarker(cherryMarkerOptions );
cherry_marker.setTag("Cherry");
cherry_line = map.addPolyline(new PolylineOptions().add(
new LatLng(14.612128, 120.995578),
new LatLng(14.614495, 120.998217)
)
.width(5)
.color(Color.GRAY)
);
}
The solution that I found out is adding all the '_line.remove' in all nested if-else statements. Didn't find any other solutions for easier/shorter coding. For the meantime I'll leave my solution here until I get better solutions.
//Remove lines
apple_line.remove();
banana_line.remove();
cherry_line.remove();
//Remove Markers
apple_marker.remove();
banana_marker.remove();
cherry_marker.remove();

Android GoogleMaps v2: error when adding multiple markers using 'for' loop

I need to add a given number of markers to a map using a for loop. The Log messages tell me the function to add each marker is called, but only one marker (two at most) are displayed on the map. My two functions are the following:
private void paintInMap(String description){
map.clear(); // to erase previous markers
String[] zones = getResources().getStringArray(R.array.zonas); // array of place names
String[] coord = getResources().getStringArray(R.array.coordinates); // array of place coordinates (placed in the same order)
String[] route = description.split(", "); // split the different places of the route description
for(int i=0; i<route.length; i++){
for(int j=0; j<zones.length; j++{
if(route[i].equals(zones[j])){
LatLng latLng = getCoordinates(coord[j]); // call function to get coordinates from String
placeMarker(latLng, zones[j]);
}
}
}
}
and:
private void placeMarker(LatLng coordinates, String name){
map.addMarker(new MarkerOptions()
.title(name)
.icon(BitMapDescriptorFactory.fromResource(R.drawable.gpsmap))
.position(coordinates)
.flat(true)
.rotation(90));
Log.d("PLACE", name+" added to map");
}
Apparently my code is correct, but on runtime it only displays one (or two) markers. I have checked the Log messages and the function is being called, but the markers do no appear. Moreover, one of the markers appears in an unspecified location (which corresponds to the first value of the coordinates array by the way)
Is this a runtime bug in Eclipse? How can I solve this?
map.clear(); // to erase previous markers
new AsyncTask<String, MarkerOptions, Void>() {
private void placeMarker(LatLng coordinates, String name) {
publishProgress(new MarkerOptions()
.title(name)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.gpsmap))
.position(coordinates)
.flat(true)
.rotation(90));
Log.d("PLACE", name + " added to map");
}
#Override
protected Void doInBackground(String... params) {
String[] zones = getResources().getStringArray(R.array.zonas); // array of place names
String[] coord = getResources().getStringArray(R.array.coordinates); // array of place coordinates (placed in the same order)
String[] route = params[0].split(", "); // split the different places of the route description
for (int i=0; i<route.length; i++) {
for (int j=0; j<zones.length; j++) {
if (route[i].equals(zones[j])) {
LatLng latLng = getCoordinates(coord[j]); // call function to get coordinates from String
placeMarker(latLng, zones[j]);
}
}
}
return null;
}
#Override
protected void onProgressUpdate(MarkerOptions... markers) {
map.addMarker(markers[0]);
}
}.execute(description);
I finally solved it by running the for loop in the UI thread instead of doing it using an AsyncTask
......
route = descriptionRoute.split(", ");
coordinates = getCoordinates(coord);
String[] zonas = getResources().getStringArray(R.array.array_zonas_madrid);
String[] coord = getResources().getStringArray(R.array.array_coordinates);
for(int i=0; i<route.length; i++){
for(int j=0; j<zonas.length; j++){
if(route[i].equals(zonas[j])){
LatLng latLng = getCoordinates(coord[j]);
placeMarker(latLng, zonas[j]);
}
}
}
....

Unable to see multiple marker on google Map

I want to show multiple markers on a google map. My latlng coordinates are fetched from a Parse database but I am not able see marker.
My second problem is that I want to show a title that is Restaurant Name with marker, how can I do this?
This is my code:
private class putMarker extends AsyncTask> {
#Override
protected ArrayList doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Toast.makeText(getApplicationContext(),
longitude + " " + latitude, Toast.LENGTH_SHORT).show();
ParseQuery query = new ParseQuery(
"Details");
ParseGeoPoint myGeoPiont = new ParseGeoPoint(latitude,
longitude);
query.whereNear("location", myGeoPiont);
query.setLimit(10);
ob = query.find();
for (ParseObject resObj : ob) {
ParseGeoPoint location = resObj
.getParseGeoPoint("location");
restaurantName = (String) resObj.get("RestaurantName");
LatLng resLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
Toast.makeText(getApplicationContext(),
restaurantName, Toast.LENGTH_SHORT)
.show();
PiontList.add(resLatLng);
}
} catch (Exception e) {
// TODO: handle exception
}
return PiontList;
}
protected void onPostExecute(ArrayList latlngList) {
for(LatLng res: latlngList)
{
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res);
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);
}
}
}
Please help me out.
it might due to unreachability of googleMap object in onPostExecute() .
Please ensure that googleMap is declared globally.
if possible please paste whole code for better evaluation
Try this
// Create lat long points
Latlng[] point_new = new LatLng[8];
point_new[0] = new LatLng(31.5301843, 74.3207487);
point_new[1] = new LatLng(31.5214693,74.3236027);
point_new[2] = new LatLng(31.5194393, 74.3257327);
point_new[3] = new LatLng(31.4942166, 74.3004533);
point_new[4] = new LatLng(31.4864646, 74.2911203);
point_new[5] = new LatLng(31.4803596, 74.2787933);
point_new[6] = new LatLng(31.4764716, 74.2638203);
point_new[7] = new LatLng(31.4775236, 74.2628873);
// Add markers
for (int i = 0; i < point_new.length; i++) {
MarkerOptions markerOptions = new MarkerOptions()
.position(point_new[i]);
marker = mMap.addMarker(markerOptions);
marker.setTitle("Points");
marker.setSnippet("Distance = 9.6 km, Time = 20 minute/s");
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.p));
}
// Set camera to last point with Zoom level 9
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point_new[7], 9));
I see a few problems here.
As #Raghunandan mentioned, you cannot update the UI from doInBackground() so you cannot add markers from there. You can however, make your MarkerOptions objects here, and then attach them to the GoogleMap in your postExecute/or in the Activity that hosts the Google Maps.
In your onPostExecute(), you have not set any Title, or Snippet to your markers. Whenever you are creating your marker, make sure to set your title. Then when the user clicks on the marker, the default behavior shows your rest name as a title.
Code will be something like this(as also mentioned by #Inzimam Tariq IT :
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res)
.setTitle(restaurantName)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);

How can i access all marker on my GoogleMap-Object (android maps v2) and set them (in)visible?

i am currently trying to implement an ActionBar-Button that on usage sets all my markers on my GoogleMap-object visible or invisible. My problem is that i don't know how i can get a reference to all my markers once they have been created and are shown on my map. Im looking for a solution where i stash all my marker-objects into an array, that i can access in other parts of my code aswell. is this approach reasonable?
here is what i am thinking of:
private Marker[] mMarkerArray = null;
for (int i = 0; i < MainActivity.customers.size(); i++) {
LatLng location = new LatLng(mData.lat, mData.lng);
Marker marker = mMap.addMarker(new MarkerOptions().position(location)
.title(mData.title)
.snippet(mData.snippet));
mMarkerArray.add(marker);
}
and set all my markers invisible on within another method:
for (int i = 0; i < mMarkerArray.length;; i++) {
mMarkerArray[i].setVisible(false);
}
it refuses to add the markers to a Marker[]-array. how can i achieve it?
mMarkerArray.add(marker) doesnt work
i figured out an answer that also regards my customerList having customers without coordinates --> (0,0;0,0). inspired by this blog.
initialize ArrayList:
private ArrayList<Marker> mMarkerArray = new ArrayList<Marker>();
add marker to my map and to the mMarkerArray:
for (int i = 0; i < MainActivity.customers.size(); i++) {
Customer customer = MainActivity.customers.get(i);
if (customer.getLon() != 0.0) {
if (!customer.isProspect()) {
Data mData= new Data(customer.getLat(),customer.getLon(),customer.getName(),
customer.getOrt());
LatLng location = new LatLng(mData.lat, mData.lng);
Marker marker = mMap.addMarker(new MarkerOptions().position(location)
.title(mData.title)
.snippet(mData.snippet));
mMarkerArray.add(marker);
}}}
set all markers not-visible
for (Marker marker : mMarkerArray) {
marker.setVisible(false);
//marker.remove(); <-- works too!
}
Replace
private Marker[] mMarkerArray = null;
with
private List<Marker> mMarkerArray = new ArrayList<Marker>();
and you should be fine.
If you use Android Maps Extensions, you can simply iterate over all markers using
for (Marker marker : googleMap.getMarkers()) {
marker.setVisible(false);
}
without having your own List of all Markers.
You can keep a Collection of OverlayItem within your Activity or Fragment and then call MapView.getOverlays().clear() to make them "invisible" and then add them back to make them visible again. Call MapView.invalidate() after each action to cause the map to be repainted.

Categories

Resources