1

The idea is to create an ArrayList of locations and every time I save the location data in that list in the same time I draw a polyline between each two points.

My question is about the Google Maps method onLocationChanged(). I want to know if it is called automatically, I mean every time the location change, or if it is called when the user click on the button of get current location?

If someone has a better idea please let me know?

perror
  • 7,071
  • 16
  • 58
  • 85

2 Answers2

2

Basically onLocationChanged is being called everytime the location is changed. However it's bad idea to implement your code inside it, you can do something like that

public class GPSTracker  implements LocationListener{
private Location location ;
public Location getLocation(){
return this.location;
}
// .. code

 @Override
    public void onLocationChanged(Location location) {
    this.location=location;
    }

}

now in your main activity you can get location by making an object of GPSTracker then like this

GPSTracker=new GPSTracker(this);
gpsTracker.getLocation (); //this will provide you with longitude,latitude then you can control it with a thread or something like that, by calling getLongitude,getLatitude you can get the location paramter

be noted the constructor takes context as a parameter so pass the context of your activity to the GPSTracker class please check the following link

Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34
0

As you've not provided your code, I don't know that you have a separate class for getting Location or in the same activity/class.

I am assuming that you want to insert your updated location in an Arraylist and want to create a polyline connection all those points.

if I'm right, Here's what you can do.

  • Create an Arraylist global variable in your Activity

    ArrayList<LatLng> cordList = new ArrayList<>();
    
  • Create a function/method call in onLocationChanged()

    locationMarkers(location);
    //passing updated location to the function/method.
    

    (If you have a separate class for getting location then get the reference of your activity in it and call this method using that reference.)

  • Then create this method in your activity.

    public void locationMarkers(Location location){
    cordList.add(new LatLng(location.getLatitude(), location.getLongitude()));
    Polyline line =googleMap.addPolyline(newPolylineOptions().width(6).color(Color.GREEN));
    line.setPoints(cordList);
    }
    

This way you'll have a polyline on the map of your locations.
Also this polyline will be a straight line between two markers/positions.
If you want it to be on the road, use HashMap.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50