0

I am having trouble by my marker because everytime the Latitude and Longitude changed, it will create a new marker instead of overriding the old one. I am fetching multiple markers so I stored it inside and ArrayList. And also my String busRoute and int passenger turns to be null. So here's my code. I hope someone can figure out my problem.

private String name, busNum, busRoute, currentLocation, estimatedTime, availableSeat, lat, lng;
double latitude, longitude;
int passenger;

public void markerDriver() {
    markerArray = new ArrayList<>();
    Firebase ref = new Firebase(Config.FIREBASE_URL_DRIVER);
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getChildrenCount() == 0) {
                markerInfo();
            } else {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    if (snapshot.child("availableSeat").exists() && snapshot.child("latitude").exists() && snapshot.child("longitude").exists() && snapshot.child("estimatedTime").exists()) {
                        name = snapshot.child("driversName").getValue().toString().trim();
                        busNum = snapshot.child("busNum").getValue().toString().trim();
                        lat = snapshot.child("latitude").getValue().toString().trim();
                        lng = snapshot.child("longitude").getValue().toString().trim();
                        availableSeat = snapshot.child("availableSeat").getValue().toString().trim();
                        estimatedTime = snapshot.child("estimatedTime").getValue().toString().trim();
                        latitude = Double.valueOf(lat);
                        longitude = Double.valueOf(lng);

                        convertLatLong();
                        getTotalPass();
                        markerArray.add(new Driver(name, busNum, busRoute, passenger, latitude, longitude, currentLocation, estimatedTime));
                    }
                }
                for (i = 0; i < markerArray.size(); i++) {
                    createMarker(markerArray.get(i).getDriversName(), markerArray.get(i).getBusNum(), markerArray.get(i).getRoute(), markerArray.get(i).getTotalPassenger(), markerArray.get(i).getLatitude(), markerArray.get(i).getLongitude(), markerArray.get(i).getLocation(), markerArray.get(i).getEstimatedTime());
                }
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Toast.makeText(MainMapActivity.this, "markerDriver: " + firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

public void convertLatLong() {
    Geocoder geocoder;
    List<android.location.Address> addresses;
    geocoder = new Geocoder(this, Locale.getDefault());

    try {
        addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.get(0).getAddressLine(0) != null) {
            currentLocation = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getLocality();
        } else {
            currentLocation = addresses.get(0).getLocality();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void getTotalPass() {
    busRef = new Firebase(Config.FIREBASE_URL_BUSNUMBER);
    Query bus = busRef.orderByChild("busNum").equalTo(busNum);
    bus.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                passenger = Integer.valueOf(snapshot.child("capacity").getValue().toString().trim()) - Integer.valueOf(availableSeat);
                busRoute = snapshot.child("route").getValue().toString().trim();
                Toast.makeText(MainMapActivity.this, "routeGetTotalPass: " + busRoute + ":::" + passenger, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Toast.makeText(MainMapActivity.this, "getTotalPass: " + firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

createMarker

protected void createMarker(String driversName, final String busNum, String route, final int totalPass, double latitude, double longitude, String location, String estimatedTime) {
    Marker marker = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .title(location)
            .snippet("Driver's Name: " + driversName + "\nBus number: " + busNum + "\nRoute: " + route + "\nTotal Passenger: " + totalPass + "\nEstimated time: " + estimatedTime));
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker) {
            dialogInfo(marker);
            return true;
        }
    });
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
qqrrrr
  • 575
  • 2
  • 8
  • 22

4 Answers4

0

Remove the old marker before add new marker

                   if (marker != null) {
                    marker.remove();
                    } 
                    convertLatLong();
                    getTotalPass();
                    markerArray.add(new Driver(name, busNum, busRoute, passenger, latitude, longitude, currentLocation, estimatedTime));

another way is clear GoogleMap before add new marker

googleMap.clear();

before onCreate declare

Marker marker;

then change

 protected void createMarker(String driversName, final String busNum, String route, final int totalPass, double latitude, double longitude, String location, String estimatedTime) {
marker = mMap.addMarker(new MarkerOptions()
        .position(new LatLng(latitude, longitude))
        .title(location)
        .snippet("Driver's Name: " + driversName + "\nBus number: " + busNum + "\nRoute: " + route + "\nTotal Passenger: " + totalPass + "\nEstimated time: " + estimatedTime));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker) {
        dialogInfo(marker);
        return true;
    }
});
}
sasikumar
  • 12,540
  • 3
  • 28
  • 48
0

First declare a list of marker ArrayList<Marker> markerList=new ArrayList<>(); then change your method create marker to

protected void createMarker(String driversName, final String busNum, String route, final int totalPass, double latitude, double longitude, String location, String estimatedTime) {
    boolean isOld = false;
    for (Marker m:markerList) {
        if (m.getTitle().equals(location)) {
            m.setPosition(new LatLng(latitude, longitude));
            isOld=true;
            break;
        }
    }
    if (!isOld) {
        Marker marker = mMap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .title(location)
                .snippet("Driver's Name: " + driversName + "\nBus number: " + busNum + "\nRoute: " + route + "\nTotal Passenger: " + totalPass + "\nEstimated time: " + estimatedTime));
    markerList.add(marker);
    }
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker) {
            dialogInfo(marker);
            return true;
        }
    });
}

this is working for me

Arjun Gurung
  • 431
  • 3
  • 17
  • Hi arjun, I am storing a `POJO` on my markerArray. as you can see on the above codes, I have a POJO model `Driver` – qqrrrr Oct 03 '16 at 04:49
  • hi arjun, can you please give me sample code on how to add a data inside that markerList? – qqrrrr Oct 03 '16 at 13:20
  • 1
    @tin in createMarker method of mine if there is existing marker it will update otherwiese create a new on.Only changing your code with mine will do your work – Arjun Gurung Oct 04 '16 at 03:26
0

If you want to remove particular marker then use weakhash map with integer as id and marker object then you can remove it on the basis of index id.

For more check this - https://stackoverflow.com/a/35363423/2128166

Community
  • 1
  • 1
Wasim K. Memon
  • 5,979
  • 4
  • 40
  • 55
0

I made it with the following code:

    final WeakHashMap<String,Marker> obj = new WeakHashMap<>();

    mRootRef.child("Coordinates/" + mRequestID)
    .addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            Coordinates coordinates = dataSnapshot.getValue(Coordinates.class);
            final String lat = coordinates.getLatitude();
            final String lng = coordinates.getLongitude();

            latLng1 = new LatLng(Double.valueOf(lat), Double.valueOf(lng));
            markerOptions = new MarkerOptions()
                    .position(latLng1);


            mapa.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng1, 15));
            mapa.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);

            Marker marker = mapa.addMarker( markerOptions);
            marker.setSnippet(dataSnapshot.getKey());
            marker.showInfoWindow();

            // Here is where I create the unique marker identification
            obj.put(dataSnapshot.getKey(), marker);


        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {


              Coordinates coordinates = dataSnapshot.getValue(Coordinates.class);
         final String lat = coordinates.getLatitude();
         final String lng = coordinates.getLongitude();

         latLng1 = new LatLng(Double.valueOf(lat), Double.valueOf(lng));
         markerOptions = new MarkerOptions().position(latLng1);

         // Now, it's just needed to update its new position
         obj.get(dataSnapshot.getKey()).setPosition(latLng1);

         mapa.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng1, 15));
         mapa.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);


        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
Rubin Luiz
  • 11
  • 2