Christian
Christian

Reputation: 111

Dynamically updating a marker in Google Maps Android

I'm sorry to post such a seemingly dumb question, but how do I go about dynamically updating a map marker without user interaction? What I have in mind something like Uber, where you see on the map a marker representing a car which moves on the map based on gps coordinates it is receiving from some server somewhere.

I have never worked with dynamic real time data so I'm not sure what is the proper Android paradigm to be using.

I have a web app currently generating GPS coordinates. I want my app to be constantly polling my web server for updated coordinates and then moving an existing marker on my android app based on those coordinates.

How do I go about doing this? AsyncTask? A service? a while loop!?!

Thank you for any pointers

Upvotes: 2

Views: 1439

Answers (1)

matiash
matiash

Reputation: 55350

An AsyncTask isn't really suited for this kind of task. From the documentation:

AsyncTasks should ideally be used for short operations (a few seconds at the most.)

For the scenario you describe, there are two possible solutions that would be a better fit: either a long-running Thread, or a Service. A service would be especially useful if you want this polling to continue even if the application is currently in the background (which, however, wouldn't seem to be the case here).

I would recommend creating a new Thread when you create the activity or fragment, and run a poll/sleep loop. Be sure to interrupt this thread whenever the Activity is paused (in onPause()), and resume it in onResume(). Also, be sure to update the MapView only from the UI thread -- this is a requirement in Android programming. You can use a Handler to do this.

Be mindful that constant polling can cause a significant impact on battery life. Depending on the update frequency and other criteria, you may consider alternatives (such as using GCM). I recommend you take a look at the "Transferring Data Without Draining the Battery" section of the training docs.

Upvotes: 3

Related Questions