rizwan dawood
rizwan dawood

Reputation: 65

How to move marker in googlemap while getting different latitude,longitude in android

I am developing android application and my requirement is, how to move marker in google map while latitude and longitude is changing which means tracking device system

This is my json

{
 "gpslocation": [
                   {
                      "Latitude":"12.9789702",
                      "Longitude":"77.6411031",
                      "UpdatedOn":"2015-06-02 14:09:02"
                   }
                ]
}

This is my main activity

  private static String url = "http://example.com/android/gps/latlong.php";

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.gmap_direction);

                pd = new ProgressDialog(Bustracking.this);
                pd.setMessage("Please wait...");
                pd.setCanceledOnTouchOutside(false);
                pd.show(); 

                new AsyncTask<Void, Void, Void>()
                {
                    @Override
                    protected Void doInBackground(Void... params)
                    {
                        callAsynchronousTask();

                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result)
                    {
                    }
                }.execute();


            }

       public void callAsynchronousTask() {
           timer = new Timer();
           timer.scheduleAtFixedRate(new TimerTask() {

             @Override
             public void run() {
                 location();     
             }
          }, 0, 1000);
         }

    public void location(){         

     List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("key", "agile89rise98"));
        params.add(new BasicNameValuePair("username", un));
        params.add(new BasicNameValuePair("type", "parent"));

         // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);

     try {                              
             JSONArray a= json.getJSONArray(TAG_SUCCESS);
             JSONObject c = a.getJSONObject(0);

             // Storing  JSON item in a Variable
         final String latitudee = c.getString("Latitude");
         final String longitudee = c.getString("Longitude");
         final String updatedon = c.getString("UpdatedOn");
         pd.dismiss();

             runOnUiThread(new Runnable(){

                @Override
               public void run() {

               try {
                        // Loading map
                        initilizeMap();

                   // Changing map type
                        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                        googleMap.setMyLocationEnabled(true);
                        // Enable / Disable zooming controls
                        googleMap.getUiSettings().setZoomControlsEnabled(false);
                        // Enable / Disable my location button
                        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                        // Enable / Disable Compass icon
                        googleMap.getUiSettings().setCompassEnabled(true);
                        // Enable / Disable Rotate gesture
                        googleMap.getUiSettings().setRotateGesturesEnabled(true);
                        // Enable / Disable zooming functionality
                        googleMap.getUiSettings().setZoomGesturesEnabled(true);
                        double latitude =  Double.parseDouble(latitudee);
                        double longitude = Double.parseDouble(longitudee);

          MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(updatedon);
          marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

                            googleMap.addMarker(marker);

                                CameraPosition cameraPosition = new CameraPosition.Builder()
                                        .target(new LatLng(latitude,
                                                longitude)).zoom(25).build();

                                googleMap.animateCamera(CameraUpdateFactory
                                        .newCameraPosition(cameraPosition));



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

                  });

            } catch (final JSONException e) {
                 pd.dismiss();
                 runOnUiThread(new Runnable(){

                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "Bus Service Not Available", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                 });
            }

        }

My lat and long is continuously changing according to device location and i am gettting lat and long from json url and display it in google map i have one AsyncTask in my oncreate function and i am calling one function called callAsynchronousTask(); in doinbackground This is function is excuting every one second because i need continuous lat,long from json url and i am calling one more funtion from callAsynchronoustask called location(); This function for retrieving lat,long value and display it in googlemap

i am calling location(); each and every seconds because of getting continous lat,long values. Now My output is coming like creating marker for each every movement so whenever i am getting latlong at that it is creating new marker

My Reqiurement:- It should not create new marker, same marker should move whenever i am getting different latlong values

Could you please tell me how to do it?

Upvotes: 0

Views: 2094

Answers (3)

Pankaj
Pankaj

Reputation: 8058

Do this between your initializeMap() method and googleMap.setMapType() method put this line:

 // Loading map
                            initilizeMap();
                          googleMap.clear();   // put this line

                       // Changing map type
                            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

Upvotes: 1

Dalija Prasnikar
Dalija Prasnikar

Reputation: 28516

You don't have to recreate marker every time you want to move it.

First, create global Marker field

GoogleMap googleMap;
Marker activeMarker = null; 

then create marker only if it is not created yet, and just move it if it is.

if (activeMarker == null)
{
   MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(updatedon);
          marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
    activeMarker = googleMap.addMarker(marker);
}
else
{
    activeMarker.setPosition(new LatLng(latitude, longitude));
    activeMarker.setTitle(updatedon);
} 

Also you should run following map initialization code only once, before you start running your location() task.

// Loading map
initilizeMap();

// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button

googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);

Upvotes: 0

Shishir Shetty
Shishir Shetty

Reputation: 2049

Some Google engineers have provided a nice demo video with some elegant sample code about how to animate markers from a starting point to an ending point, for all various versions of Android:

The relevant code is here:

https://gist.github.com/broady/6314689

And a nice demo video of all of it in action.

http://youtu.be/WKfZsCKSXVQ

OLD DEPRECATED ANSWER BELOW

In the documentation, it is mentioned that Marker Icons cannot be changed:

Icon

A bitmap that's displayed for the marker. If the icon is left unset, a default icon is displayed. You can specify an alternative coloring of the default icon using defaultMarker(float). You can't change the icon once you've created the marker. Google Maps API v2 Documentation

You're going to have to keep track of specific markers, perhaps using a method similar to that described here: Link a Marker to an Object, then figure out which marker you need to update. Call .remove() on the marker, then create a rotated image depending on the "direction" you want, create a new Marker with that image, and add the new Marker to the map.

You do not need to "clear" the map, simply remove the marker you want to modify, create a new one, then add it back to the map.

Unfortunately, the new Maps API is not very flexible yet. Hopefully Google continues to improve upon it.

Upvotes: 0

Related Questions