Android - Removing markers when changing different maps - android

I have created an app that displays different tracks in a park. I have created two markers which represent the start and end of the track. I am getting a problem where when I change tracks, the marker from the previous track still shows. I tried map.clear() but that removed everything. I want to not show the markers from the previous track.
private void createMarker(double latitude, double longitude, String title) {
map.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
}
private void updateMapTrack() {
switch (options.getTrack()) {
case TRACK1:
createMarker(-45.85696303760779, 170.5199563062967, "Start of track1.");
createMarker(-45.85808344124618, 170.5247490755895, "End of track1.");
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-45.856895, 170.518673), (float) 17.8));
break;
case TRACK2:
createMarker(-45.85696303760779, 170.5199563062967, "Start of track2.");
createMarker(-45.85808344124618, 170.5247490755895, "End of track2.");
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-45.857144, 170.522713), (float) 16.32));
break;
case TRACK3:
createMarker(-45.85714008365828, 170.5193834664067, "Start of track3.");
createMarker(-45.85751258570694, 170.526808129631, "End of track3.");
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-45.858164, 170.523111), (float) 16));
break;
}
}

You will have to keep the reference to the Marker Object you created and then you have to call
[Marker Reference].remove() method to remove it from the GoogleMap.
for Example:
Create Marker like this and save the reference:
Marker startTrackMarker = createMarker(-45.85696303760779, 170.5199563062967, "Start of track1.");
And that is how you will remove:
startTrackMarker.remove()
And your createMarker method will be changed like this:
private Marker createMarker(double latitude, double longitude, String title) {
return map.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
}
Note:
If you have multiple markers then you will need an array to hold all the references to the markets like this:
ArrayList<Marker> markers = new ArrayList<>();
and then to remove these markers you will have to iterate the array and call remove() on every marker object. (Otherwise, it all depends upon your logic).

Related

Android Google Map showing multiple markers on current location

Hello everyone I am using custom marker image in google map. My problem is that when i click on that marker or zoom in or zoom out this marker duplicates means, more markers appears on the same location on different points. why this happening? how to avoid it?
Thanks in advance.
Code
#Override
public void onLocationChanged(Location location)
{
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
MarkerOptions markerOptions = new MarkerOptions();
// Setting position for the marker
markerOptions.position(latLng);
// Setting custom icon for the marker
// markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.compass_needle));
// Setting title for the infowindow
// Adding the marker to the map
googleMap.addMarker(markerOptions);
// markerOptions.rotation(260);
}
You are adding markers but you are not clearing previous added loation marker so You have to clear previously added marker when Location is changed again.
Add this line above googleMap.addMarker(markerOptions);
googleMap.clear();
googleMap.addMarker(markerOptions);
I hope it helps!
More correct is to remove a specific marker, and don't clear the whole map.
Because you can have others markers and polylines on map.
In your case you have only one marker showing user location.
You can get it when adding.
private Marker mLocationMarker;
public void onLocationChanged(Location location) {
...
if(mLocationMarker != null) {
mLocationMarker.remove();
}
mLocationMarker = googleMap.addMarker(markerOptions);
}

Look if current location is near marker

I have a Google Maps API Activity and want the markes only to be clickable if the user is in a certain radius to them.
How is the best way to do this?
This is how I set my markers:
Marker marker1 = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(49.793012, 9.926201))
.title(getString(R.string.Title1))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
Marker marker2 = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(49.792742, 9.939118))
.title(getString(R.string.Title2))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
Marker marker3 = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(49.793349, 9.932558))
.title(getString(R.string.Title3))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
Solution code:
LatLng markerPosition = marker.getPosition();
myLocation = locationManager.getLastKnownLocation(provider);
Location markerLoc = new Location("marker");
markerLoc.setLatitude(markerPosition.latitude);
markerLoc.setLongitude(markerPosition.longitude);
float meters = myLocation.distanceTo(markerLoc);
You can get the LatLng of the markers by marker.getPosition(); then you can compare it with the CurrentLocation. To do this, you can check this post, and next you can make clickable or notclickable a marker as follows:
getMap().setOnMarkerClickListener(new OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
onMapClick(marker.getPosition());
return true;
}
});
If you return true for the function, it means that you've accepted the occurred click event on your marker; otherwise, you've not accepted it.
Moreover, you can do it with:
MarkerOptions.clickable and Marker.setClickable.
This is just a guide who how I would do what you want. hope it helps. :)

android detect various circles on a map v2

In my little app I have a map and i'm parsing an XML from the web, like this:
<place>
<lat>42.827602</lat>
<lon>-1.663957</lon>
<place_name>Place one</place_name>
<snippet>Snippet de place Facebook</snippet>
<thumb>http://www.animage.com/myicon1.png</thumb>
</place>
<place>
<lat>42.830750</lat>
<lon>-1.669064</lon>
<place_name>Place two</place_name>
<snippet>Snippet de place Twitter</snippet>
<thumb>http://www.animage.com/myicon2.png</thumb>
</place>
<place>
<lat>42.825333</lat>
<lon>-1.668232</lon>
<place_name>Place Three</place_name>
<snippet>Snippet de place Skype</snippet>
<thumb>http://www.animage.com/myicon3.png</thumb>
</place>
</response>
every time I read a "place" from the xml, the onPostExecute of my AsyncTask, calls the method that creates a new marker and circle on the map of my application
For example, if the xml has seven "places", the method to create a new marker and a circle is called seven times.
Marker aMarker;
Circle aCircle;
//...
public void createNewMarkerAndCircle() {
//...
aMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(dLat, dLon))
.title(nombre_punto)
.snippet(introduccion_punto)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
aCircle = mMap.addCircle(new CircleOptions()
.center(new LatLng(dLat, dLon))
.radius(150)
.strokeColor(Color.RED)
}
//...
public void onPostExecute(String xml) {
xml = stringBuffer.toString();
try {
Document doc = parser.getDomElement(xml);
NodeList nl0 = doc.getElementsByTagName(KEY_PLACE);
Element e = (Element) nl0.item(lap);
theLat = parser.getValue(e, KEY_LATITUDE);
theLon = parser.getValue(e, KEY_LONGITUDE);
//...
createNewMarkerAndCircle();
//...
So far, everything works fine and markers and circles are created on the map.
My purpose is that when the user on the map comes within the radius of one of the circles, get the datas of the marker that is inside.
I show you what I'm doing:
I have a listener of my location that every time it´s updated, check the distance from the current location and radius of the circle.
GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
float[] distance = new float[2];
try {
Location.distanceBetween(
location.getLatitude(),
location.getLongitude(),
aCircle.getCenter().latitude,
aCircle.getCenter().longitude, distance);
if (distance[0] > aCircle.getRadius()) {
Log.i("myLogs", "Outside");
} else {
String markerTitle;
markerTitle = aMarker.getTitle();
Log.i("myLogs", "I´ in the circle" + " " + markerTitle);
}
//....
This works fine, but with a big problem.
When I start to walk the route, only detected when I go into the last "place" parsed from xml, and therefore, the last marker and circle created.
I understand what the problem is, the last marker (Marker aMarker;) and circle (Circle aCircle;) created are those with the values assigned ... But i do not know how to fix it.
I would appreciate any help, several days ago I'm looking for solutions, but without success.
Thanks and regards.
More information:
I found this other way , but the problem remains exactly the same:
https://gist.github.com/saxman/5347195
the last marker (Marker aMarker;) and circle (Circle aCircle;)
created are those with the values assigned ... But i do not know how
to fix it.
In order to check the distance against all the points of interests you create you need to hold them in some sort of structure, the most simple being a list, to reference them later in the listener:
Marker aMarker;
Circle aCircle;
// this will hold the circles
List<Circle> allCircles = new ArrayList<Circle>();
// this will hold the markers
List<Marker> allMarkers = new ArrayList<Marker>();
public void createNewMarkerAndCircle() {
aMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(dLat, dLon))
.title(nombre_punto)
.snippet(introduccion_punto)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE )));
// store the new marker in the above list
allMarkers.add(aMarker);
aCircle = mMap.addCircle(new CircleOptions()
.center(new LatLng(dLat, dLon))
.radius(150)
.strokeColor(Color.RED)
// store the created circles
allCircles.add(aCircle);
}
// in the LocationListener iterate over all stored circles and check the distances against each one of them
// as you add the circles and markers in the same method you'll have a correspondence between them in the two lists
// another sensible approach would be to create a custom Area class
// to hold both the Marker and the circle in one single place
// so when you find yourself inside a circle the marker will be at the same position in allMarkers
for (int i = 0; i < allCircles.size(); i++) {
Circle c = allCircles.get(i);
Location.distanceBetween(location.getLatitude(), location.getLongitude(), c.getCenter().latitude, c.getCenter().longitude, distance);
if (distance[0] > c.getRadius()) {
Log.i("myLogs", "Outside");
} else {
String markerTitle;
markerTitle = allMarkers.get(i).getTitle();
Log.i("myLogs", "I´ in the circle" + " " + markerTitle);
// you found a circles so you may want to break out of the for loop, break;
}
GeofencingApi was created exactly for this purpose: https://developer.android.com/reference/com/google/android/gms/location/GeofencingApi.html
I think you make mistake createNewMarkerAndCircle(), Please make MarkerOptions and Circle local else when update map only last instance of show, that is reason that only last circle show.
public void createNewMarkerAndCircle() {
//...
MarkerOptions aMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(dLat, dLon))
.title(nombre_punto)
.snippet(introduccion_punto)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
Circle aCircle = mMap.addCircle(new CircleOptions()
.center(new LatLng(dLat, dLon))
.radius(150)
.strokeColor(Color.RED)
}

Create Marker but not show it on the map

I would like to know how I can create a Marker but not to show on the map, I'm saving the Markers in an array but it is showing me on the map, this is my code
if (c4!= null ) {
if (c4.moveToFirst()) {
do {
LatLng posicion = new LatLng(
Double.parseDouble(c4.getString(0)),
Double.parseDouble(c4.getString(1)));
punto = googleMap.addMarker(new MarkerOptions() .position(posicion)
.title(c4.getString(2))
.snippet(year)
.anchor(0.5f, 0.5f));
mMarkers.add(punto);
}while (c4.moveToNext());
}
}
I've tried and used this
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude));
but this does not work for me as I need to be type Marker.
Anyone know how could i save spots without paint on the map? thank you very much and sorry for my bad English :)
Try using:
punto = googleMap.addMarker(new MarkerOptions() .position(posicion)
.title(c4.getString(2))
.snippet(year)
.anchor(0.5f, 0.5f).visible(false));
instead of
punto = googleMap.addMarker(new MarkerOptions() .position(posicion)
.title(c4.getString(2))
.snippet(year)
.anchor(0.5f, 0.5f));
Notice the .visible(false) part.
For further info regarding the same refer: http://developer.android.com/reference/com/google/android/gms/maps/model/MarkerOptions.html
save the markers in this list
List<Marker> markers = new ArrayList<Marker>();
markers.add(marker); // here the marker is of google map
Then afterwords use Clear() on your google map so that the markers that got add should be deleted
EDIT=
Also you can separately remove a single marker by
marker.remove();
you can also try to save the latitude and longitude in array list and then later as you like it, show them through marker.

Google map markers are disappearing instantly. How to make a marker remain constant?

I am adding markers on my map by fetching user locations stored in the remote server. The locations are displayed but within 3 seconds, the marker disappears. Any solution to this?? Below is my complete code.
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
for(Users u:locList)
{
MarkerOptions markerOptions = new MarkerOptions();
double latitude1 = u.getLatitude();
double longitude1 = u.getLongitude();
LatLng latLng1 = new LatLng(latitude1, longitude1);
// Animating to the touched position
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng1));
if(userMarker!=null) userMarker.remove();
markerOptions = new MarkerOptions().position(new LatLng(latitude1, longitude1)).title(latLng1.toString());
// adding marker
userMarker = mGoogleMap.addMarker(markerOptions);
//userMarker.setVisible(true);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
markerOptions.visible(true);
}
}
please check your code do you use something like map.clear()
remove
userMarker.remove();
from your code...
I fixed the same issue by commenting out map.clear. Wow correct my grammar way to go get a life

Categories

Resources