Home » Android » How to refresh markers on Map in android?

How to refresh markers on Map in android?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to refresh markers in map,my map contains different locations with current location. if server side add any location then add that marker in my map.

How can I refresh my markers without load map ?

My code

if(arl.size()!=0){
                for(int j = 0;j<arl.size();j++){


              String lat =arl.get(j).get("lat").toString();
              String lng =arl.get(j).get("lng").toString();
              if ( !lat.trim().equals("") && !lng.trim().equals("") ) {
              double Hlat = Double.parseDouble(lat.trim());
              double Hlong= Double.parseDouble(lng.trim());

              LatLng dabaseLocations =new LatLng(Hlat, Hlong);

              Marker HYD = _googleMap.addMarker(new MarkerOptions()

              .position(dabaseLocations)
              .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
              .flat(true));

              // Show current location with database locations

              _googleMap.clear();
                _googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition)); 
                Marker m=_googleMap.addMarker(new   
         MarkerOptions().position(myPosition).title("start"));
               // m.setPosition(new LatLng(5,5));

                 }
               }

         }
             else{

                 // Show only Current Location

            _googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition)); 
            _googleMap.addMarker(new     
       MarkerOptions().position(myPosition).title("start"));

        }
How to&Answers:

Save the instance of all markers which you are going to update and then Remove marker when location gets updated

private Marker mCustomerMarker;

if (mCustomerMarker != null) {
            mCustomerMarker.remove();
        }

and Re-draw them again

     LatLng mCustomerLatLng = new LatLng(latitude, longitude);
     MarkerOptions options = new MarkerOptions();
     options.position(mCustomerLatLng);
     options.title(getResources().getString(R.string.pickup_marker));
            options.icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.green_pin));

Adding the marker in the Google Map

mCustomerMarker = googleMap.addMarker(options);