Draw a polyline in Android google maps as the user move

2.4k views Asked by At

Hy, I'm a newbie in Android, and I've learned about android google maps. I'd like to tracking user movement and draw polyline path in android google maps in real time, can someone help me with the example? I can get the location chage interval but still don't know how to apply it into polyline and keep the data LatLng into array.

1

There are 1 answers

0
Charuක On

You need to add this/related g.play services virsion line in your gradle in case you haven't.

compile 'com.google.android.gms:play-services-maps:8.4.0'

As official doc says , use this code.

GoogleMap map;
 // ... get a map.
 // Add a thin red line from London to New York.
 Polyline line = map.addPolyline(new PolylineOptions()
     .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
     .width(5)
     .color(Color.RED));

Note: Methods that modify a Polyline must be called on the main thread If not, an IllegalStateException will be thrown at run-time.

For a sake that i know you can find this code so here is my small logic

  1. Keep start and end position Latlng variables (startLatlng ,endLatlng)
  2. As you can see in the example you cannot send hard coded values,pass your real values so take the location when user moves or may be after a certain time period
  3. Write logic : startLatlng = new Latlng data that you got when user move / after a time period;
  4. only for the first time startLatlng = endLatlng (use if condition with a boolian and change its value after it gets called )
  5. call your method to draw Poly-line line with (startLatlng and endLatlng)
  6. endLatlng = startLatlng (see only after you call that draw method set the start value to end value)

Note

If it's confusing use real values and try to understand what i explained. First time both are same. It darws a dot because both are in the same spot.(i guess) Now startLatlng & endLatlng both have the first same value.

Second time new location comes startLatlng changes.Then it cannot go to that boolean if method because it's only for the first time.

Now it call that method to draw line (new startLatlng and old endLatlng). Only after you call that draw method, your endLatlng gets that new startLatlng value.

But the next time when your full logic gets called with a very new data again that very new data assigns to startLatlng.

So in this way it can draw a line between the startLatlng (new Possition) to endLatlng (oldPossition).