android marker remove() method not working - android

I use List to store marker to add to gmap and remove component it self.
List<Location> listLocation = new ArrayList<Location>();
When location updated. I were store Location to listLocation,remove the old marker . Then add the newest location to Gmap.
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
countUpdatePos++;
listLocation.add(location);
LatLng lastLocation = new LatLng(location.getLatitude(),
location.getLongitude());
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastLocation, 16));
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
int a = addresses.get(0).getMaxAddressLineIndex();
for (int i = 0; i < a; i++) {
if (i == 0) {
cityName = addresses.get(0).getAddressLine(i);
} else {
cityName = cityName + ", "
+ addresses.get(0).getAddressLine(i);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
if (countUpdatePos == 1) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.updated_position), 2000)
.show();
progressToLoadMap.setVisibility(View.GONE);
checkStartActivity = true;
timer = new MyCount((int) totalTime * 60 * 1000, 1000);
timer.start();
}
if (listLocation.size() > 1) {
listLocation.add(location);
// gmap.clear();
LatLng newLocation = new LatLng(location.getLatitude(),
location.getLongitude());
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(newLocation, 16));
myMarker = gmap.addMarker(new MarkerOptions().position(new LatLng(
listLocation.get(listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1).getLongitude())));
if (myMarker != null) {
myMarker.remove();
myMarker = null;
}
gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
if (listLocation.get(listLocation.size() - 1) != null
&& listLocation.get(listLocation.size() - 1) != null) {
gmap.addPolyline(new PolylineOptions()
.add(new LatLng(listLocation.get(
listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1)
.getLongitude()),
new LatLng(location.getLatitude(), location
.getLongitude())).width(3)
.color(Color.BLUE));
}
But when run activity, all marker still display, and no polyline add to gmap :(. Help me
here is picture

I hade the same problem and after checking my code I found that I am calling the method that add the marker twice in the oncreate and onresume events so 2 markers are added at the same position on the map so when I remove the marker using marker.remove() method one is removed but the other one remain so I thought it is not deleted. I removed the method call from the oncreate event and now it is working fine.

What you have done is correct but Just need little bit modification for Marker:
Set this globally:
Marker myMarker;
In you onCreate()
myMarker = gmap.addMarker(new MarkerOptions()
.position(new LatLng(listLocation.get(
listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1)
.getLongitude())));
Then Whenver you want to add another Marker then Just check it out if Is there already any other marker is present. If yes then remove it if you want.
For that:
if(myMarker!=null)
{
marker.remove();
marker = null;
}
myMarker = gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
For Polyline you might check if lat,long are not null.

I've seen something like this before.
try making
//put this at the top of your class
Marker myMarker;
//this is using the reference
myMarker = gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
myMarker.remove();
an instance variable. WHen you call remove() it needs to be the same marker that you added.
make sure you keep a reference to the marker :
myMarker = gmap.addMarker(new MarkerOptions()
.title(getResources().getString(
R.string.current_location_found)).snippet(cityName)
.position(newLocation));
if (listLocation.get(listLocation.size() - 1) != null
&& listLocation.get(listLocation.size() - 1) != null) {
gmap.addPolyline(new PolylineOptions()
.add(new LatLng(listLocation.get(
listLocation.size() - 1).getLatitude(),
listLocation.get(listLocation.size() - 1)
.getLongitude()),
new LatLng(location.getLatitude(), location
.getLongitude())).width(3)
.color(Color.BLUE));

Related

How Can i Show multiple location marker with optimize Distance and draw line to connect each others

I have already try to achieve this type of functionality using google map direction API. You can see the picture I found this in javascript code but I want to do in android.
I want to achieve like this please click here..
PolygonOptions rectOptions2;
rectOptions2= new PolygonOptions();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick( final LatLng latLng)
{
// PolylineOptions rectOptions = new PolylineOptions()
// .add(new LatLng(latitude, longitude));
// Polyline polyline = mMap.addPolyline(rectOptions);
// Creating a marker
BitmapDescriptor icon =
BitmapDescriptorFactory.fromResource(R.drawable.ic_map);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions .icon(icon);
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
final List<Address> listAddresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
markerOptions.title(location);
location = listAddresses.get(0).getAddressLine(0);
latitude=latLng.latitude;
longitude=latLng.longitude;
}
} catch (IOException e) {
e.printStackTrace();
}
// mMap.clear();
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.addMarker(markerOptions);
lat=latitude;
lng=longitude;
rectOptions2.add(new LatLng(lat, lng));
polygon= mMap.addPolygon(rectOptions2);
polygon.setStrokeColor(Color.RED);
polygon.setFillColor(Color.BLUE);
//add lat and lng in arraylist here
}
});

Drawing a polyline from current location to a fixed location

Okay, so I am developing a google maps like application using android studio. And right now I am having difficulty in understanding it. So my problem is I cannot set a specific destination that I want to go to and then draw a polyline going to it. Can somebody please help me. Thanks in advance
PolygonOptions rectOptions2;
rectOptions2= new PolygonOptions();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick( final LatLng latLng)
{
// PolylineOptions rectOptions = new PolylineOptions()
// .add(new LatLng(latitude, longitude));
// Polyline polyline = mMap.addPolyline(rectOptions);
// Creating a marker
BitmapDescriptor icon =
BitmapDescriptorFactory.fromResource(R.drawable.ic_map);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions .icon(icon);
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
final List<Address> listAddresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
markerOptions.title(location);
location = listAddresses.get(0).getAddressLine(0);
latitude=latLng.latitude;
longitude=latLng.longitude;
}
} catch (IOException e) {
e.printStackTrace();
}
// mMap.clear();
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.addMarker(markerOptions);
lat=latitude;
lng=longitude;
rectOptions2.add(new LatLng(lat, lng));
polygon= mMap.addPolygon(rectOptions2);
polygon.setStrokeColor(Color.RED);
polygon.setFillColor(Color.BLUE);
//add lat and lng in arraylist here
}
});

Android how to animate marker from server every 10 seconds

I have a map which is loading a current address from a server. I am using on MapReady, and before its initialized it loads the first location from the server and zooms to the location. I want the app to be reading the address from the server every 10 seconds, and mapping the location. I am stuck after on MapReady on how I can remove the previous marker add the new marker from values from the server and still zoom on the location, the tutorials I have read like this haven't been so helpful. Below is my on MapReady.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
geocoder = new Geocoder(getActivity());
try {
ArrayList<Address> current_adresses = (ArrayList<Address>) geocoder.getFromLocationName(current_location, 1);
for(Address add : current_adresses){
if (current_adresses != null) {//Controls to ensure it is right address such as country etc.
current_longitude = add.getLongitude();
current_latitude = add.getLatitude();
}
}
ArrayList<Address> to_adresses = (ArrayList<Address>) geocoder.getFromLocationName(destination, 1);
for(Address add : to_adresses){
if (to_adresses != null) {//Controls to ensure it is right address such as country etc.
to_longitude = add.getLongitude();
to_latitude = add.getLatitude();
}
}
} catch (IOException e) {
e.printStackTrace();
}
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
mMap.addMarker(new MarkerOptions()
.position(new LatLng(current_latitude, current_longitude))
.title(first_name + ", " + vehicle)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pickup)));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(to_latitude, to_longitude))
.title("Destination")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.office_building)));
CameraPosition cameraPosition= new CameraPosition.Builder()
.target(getCenterCoordinate())
.zoom(13)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(cameraPosition);
mMap.animateCamera(camUpd3);
//AsyncTask to get new address
getTransporterLocation();
/**
*
* I want to set a timer with the AsyncTask inside,
*
* remove the previous marker, convert the new address to lat and long
*
* map the marker and zoom in
*
*/
}
}
You just need to call
mMap.clear();
and repeat your steps for drawing markers.

Android Maps v2 : add multiple markers to google mapfragment

I am trying to add 2 markers to the google map with the following code. It shows only one location instead of two. Can anyone look at it and comment ? I saw that the location values are distinct with a debugger.
public void updateMapWithNewLocation() {
Marker marker1 = null;
Marker marker2 = null;
LatLng latLng1 = null;
LatLng latLng2 = null;
if (mMyLocation != null) {
latLng1 = new LatLng(mMyLocation.getLatitude(), mMyLocation.getLongitude());
MarkerOptions myMarkerOptions = new MarkerOptions()
.position(latLng1)
.title("me");
marker1 = mMap.addMarker(myMarkerOptions);
}
if (mFriendLocation != null) {
latLng2 = new LatLng(mMyLocation.getLatitude(), mMyLocation.getLongitude());
MarkerOptions friendMarkerOptions = new MarkerOptions()
.position(latLng2)
.title("friend");
marker2 = mMap.addMarker(friendMarkerOptions);
}
List<Marker> markerList = new ArrayList<>();
if(marker1 != null){
markerList.add(marker1);
}
if(marker2 != null) {
markerList.add(marker2);
}
zoomToShowAllMarkers(markerList);
}
private void zoomToShowAllMarkers(List<Marker> markers) {
if ( markers == null || markers.size() < 1)
return;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
for (Marker m : markers) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bounds.getCenter(), 10));
}
try using below code.
// Creating an instance of MarkerOptions
MarkerOptions markerOptions1 = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions1.position(LatLng1);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions1);
// Creating an instance of MarkerOptions
MarkerOptions markerOptions2 = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions2.position(LatLng2);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions2);
or you can add using loop inside the your custom method.
This is how I did to zoom with bounds:
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 20);
map.animateCamera(cameraUpdate);
}
});
The onMapLoaded() makes the zooming done after the map got loaded.
Hope this helps.
Thanks for your suggestions and looking at it.
I had a copy/paste error of using myLocation instead of friendLocation
this particular line:
latLng2 = new LatLng(mMyLocation.getLatitude() mMyLocation.getLongitude()); <-- should use mFriendLocation instead of mMyLocation.
Sorry for the trouble.

Draw Polyline for Google map by for condition Android

I tried to draw a polyline between given markers, which are saved at an arraylist (poisMap). Based on my research I created the following code. I get no error and also no line, but the markers are all visible.
How have I to place the polyline method in order to get it working?
private void setUpMap() {
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
PolylineOptions routeDraw = new PolylineOptions().add(new LatLng(latitude,longitude)).width(5).color(Color.BLUE);
Polyline polyline = mMap.addPolyline(routeDraw);
}
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
private void setUpMap() {
PolylineOptions routeDraw = new PolylineOptions().width(5).color(Color.BLUE);
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
routeDraw.add(new LatLng(latitude,longitude))
}
Polyline polyline = mMap.addPolyline(routeDraw);
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
other
private void setUpMap() {
LatLng[] latlngarray = new LatLng[poisMap.size()];
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
latlngarray[i]= new LatLng(latitude, longitude);
}
PolylineOptions routeDraw = new PolylineOptions().add(latlngarray).width(5).color(Color.BLUE);
Polyline polyline = mMap.addPolyline(routeDraw);
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
check this it is helpfull if you use google map
[http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/][1]

Categories

Resources