4

1.In My app Gps LatLong is Getting from Server Every OneMinute. Saved in Shared Pref ,then getting the LatLong From shared pref Showing the Marker on the Map.

2.Every One Minute I want to Move the Marker based on the LatLong.

3.But While Changing the Marker Location. Getting Duplicates.

Please Help me to Solve this Issue.

Inside Oncreate method i Called below Snippet in Every 60 Secs for Calling a Method.

 try
        {
            Thread t = new Thread()
            {
                @Override
                public void run()
                {
                    try
                    {
                        while (!isInterrupted())
                        {
                            Thread.sleep(60*1000);
                            getActivity().runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {

                                    display_Location();
                                    Log.i("Every 60 Second","Current  Called..");

                                }
                            });
                        }
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            };
            t.start();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

Method Iam USing:

private void display_Location()
    {

        try
        {

            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (mLastLocation != null)
            {
        /*For Current Location ping Starts Here*/

                // get user data from session
                HashMap<String, String> user = session.getGPSPING();

                // UserLat
                String LatLongUser = "";
                LatLongUser = user.get(SessionManagerFor_Register.KEY_LATLONG);




                if (!LatLongUser.equals("") || LatLongUser != null)
                {

                    Log.i(" PING on MAP LatLong", LatLongUser);

                    String[] LanlongArr = LatLongUser.split("//");
                    List<String> Lanlonglist1 = Arrays.asList(LanlongArr);



                    int length = Lanlonglist1.size();

/*ArrayList For adding All ArrayList items in Single(Concating)*/


                    arraylist_DetailLineWalker = new ArrayList<String>(length);

                    for (int i = 0; i < length; i++) {


                        arraylist_DetailLineWalker.add(Lanlonglist1.get(i) 
                              );
                    }

                    if (arraylist_DetailLineWalker != null)
                    {

                        // Initializing
                        LineWalkermMarkers_arr = new ArrayList<Marker>();
                        //   just Remove Older Line Wlaker
                        if (LineWalkermMarkers_arr != null) {
                            // LineWalker_marker1.remove();
                            RemoveLineWalkerMarkers();

                            Log.i(TAG, "LineWalker REMOVED.............................");
                        }


                        for (int i = 0; i < arraylist_DetailLineWalker.size(); i++)
                        {
                            try 
                            {
                                String Val = arraylist_DetailLineWalker.get(i).toString();
                                //Log.i(" Validation Id",Val);
                                VALUE_ARRAY_STRING = Val.toString().split("::");

                                LatLong_DataSaveTable = VALUE_ARRAY_STRING[0].toString();



                                System.out.println("checking STarted LatLong::" + LatLong_DataSaveTable);

                                String[] latlong = LatLong_DataSaveTable.split(",");
                                double latitude1 = Double.parseDouble(latlong[0]);
                                double longitude2 = Double.parseDouble(latlong[1]);

                                //To hold location
                                LatLng latLng1 = new LatLng(latitude1, longitude2);
                                //To create marker in map
                                MarkerOptions markerOptionsLineWalker = new MarkerOptions();
                                markerOptionsLineWalker.position(latLng1); //setting position
                                markerOptionsLineWalker.draggable(true); //Making the marker draggable
                                markerOptionsLineWalker.title("USER LOCAITON");




                                    markerOptionsLineWalker.icon(BitmapDescriptorFactory.fromResource(R.drawable.walker_outof_fence_icon_red));



                                //adding marker to the map
                                // googleMap.addMarker(markerOptionsLineWalker);
                                LineWalker_marker1 = googleMap.addMarker(markerOptionsLineWalker);

                                LineWalkermMarkers_arr.add(LineWalker_marker1);
                                // LineWalker_marker1.setPosition(latLng1);
                                Log.i(TAG, " NEW Line Walkers PING Added.............................");

                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }

                        }

                    } else {
                        Log.i("MAP NEwLatLong", "TOTAL ARRY LIST NULLL");
                    }


                }
                else
                {
                    Log.i("MAP NEwLatLong", "Null Not LatLong");

                    Toast.makeText(getActivity(), "Lat Long Not Available..!", Toast.LENGTH_SHORT).show();
                }


            }
            else
            {

                Log.i("Location EXception", "Couldn't get the location. Make sure location is enabled on the device");
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                gps.showSettingsAlert();
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }


    /*Remove the Linewalker*/
    private void RemoveLineWalkerMarkers()
    {
        for (Marker marker: LineWalkermMarkers_arr)
        {
            marker.remove();
        }
        LineWalkermMarkers_arr.clear();
    }
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
Kumar
  • 969
  • 2
  • 22
  • 56
  • so basically you don't want to show old marker you just want to point out current location with one marker – Amit Gupta Jul 09 '16 at 12:11
  • @AmitGupta yes, Based on the LatLong From SharedPRef ,It Have to add New Marker or Move to that point. without Duplicates. – Kumar Jul 09 '16 at 12:14
  • why are you putting the code of add marker inside the loop you should put that code out side the loop with the last lat long which you want to display – Amit Gupta Jul 09 '16 at 12:19
  • Have you tried googleMap.clear() before load new markers? – Rahul Vats Jul 09 '16 at 12:19
  • @AmitGupta also My Situation will Come Multiple Markers(Like User1,User2 User3)from Server. it should add On the Map WIthout Duplicates.thats Why I kept inside the For Loop. – Kumar Jul 09 '16 at 12:20
  • ok i got the point but you have to create separate list of all different users with there last location – Amit Gupta Jul 09 '16 at 12:23

3 Answers3

3
if(arraylist_DetailLineWalker != null && arraylist_DetailLineWalker.size()>0){
    arraylist_DetailLineWalker.clear()
    mMap.clear();
    showMarker();
}
Akshay GS
  • 93
  • 6
2

You are calling RemoveLineWalkerMarkers() after initializing LineWalkermMarkers_arr doing LineWalkermMarkers_arr = new ArrayList<Marker>();, so you are never removing your markers.

Just initialize your LineWalkermMarkers_arr after removing the markers:

if (LineWalkermMarkers_arr != null) {
    RemoveLineWalkerMarkers();
    Log.i(TAG, "LineWalker REMOVED.............................");
}
LineWalkermMarkers_arr = new ArrayList<Marker>();

As a side note, you should follow the Java code conventions (variables and method names should start with lowercase). You can find good guides here and here

antonio
  • 18,044
  • 4
  • 45
  • 61
2

Solution is just a logic change

  1. Initialize Marker only once , either onCreate or some other method according to your logic
  2. If the markers are multiple, then re-initialization should be done once data is received.
  3. Created markers can be cleared with below logic

if(mGoogleMap != null) {
        mGoogleMap.clear();
 }
  1. Either reuse this marker to move from last location to new location. Or recreate all the markers, once data is received

//With your logic , this check should be done
if(arraylist_DetailLineWalker.size()>0){
   RemoveLineWalkerMarkers();
}
LineWalkermMarkers_arr = new ArrayList<Marker>();
for (int i = 0; i < arraylist_DetailLineWalker.size(); i++)
{
}

Alternative easy method to move single marker , to show live driving direction kind of feature

    private Marker mCurrentMarker;
    private float ZOOMLEVEL=18.0f;
    private LatLng previousLatLon;
    private Handler mLocalHandler;
    private GoogleMap mGoogleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLocalHandler = new Handler();
        previousLatLon=new LatLng(45.320372, 2.460161);
        //Initialize Marker once Google Map object is created
        mMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker_icon));
        mMarkerOptions.position(previousLatLon);
        mCurrentMarker = mGoogleMap.addMarker(mMarkerOptions);


    }

    /**
     * Call this method to move marker in map to new location in map with updated location
     * @param marker
     * @param toPosition
     * @param fromPosition
     */
    public void animateMarker(final Marker marker, final LatLng toPosition,final LatLng fromPosition) {


        final long duration = 500;
        final Interpolator interpolator = new LinearInterpolator();

        mLocalHandler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - mStartTime;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                marker.setPosition(toPosition);
                marker.setAnchor(Constants.MAPANCHOR, Constants.MAPANCHOR);
                mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(toPosition, ZOOMLEVEL));
                if (t < 1.0) {
                    // Post again 16ms later.
                    mLocalHandler.postDelayed(this, 16);
                } else {
                    marker.setVisible(true);
                }
                }
            }
        });
        previousLatLon=toPosition;// reassign the previous location to current location
    }
Sreehari
  • 5,621
  • 2
  • 25
  • 59