How can I create an array that contains latitude and longitude and use for loop to mark the positions on google map in android

android, arrays, fragment, google-maps, google-maps-api-3

Solution

Firstly, you are wanting an array that stores the LatLng object. So, declare one like so:

ArrayList<LatLng> locations;

And you also need to initialise your ArrayList:

locations = new ArrayList();

Now you can add locations to the array, using the ArrayList.add method:

locations.add(new LatLng(latitude, longitude));

Now that you have an ArrayList filled with some LatLng's, you can iterate over them using a foreach loop, like so:

for(LatLng location : locations){ 
    mMap.addMarker(new MarkerOptions() 
        .position(location)
        .title(...)
}

The above basically reads as:

For each location in the locations ArrayList, add a new marker, where the position of the marker is the location we're retrieving from out array

Tying it all together:

ArrayList<LatLng> locations = new ArrayList();
locations.add(new LatLng(30.243442, -1.432320));
locations.add(new LatLng(... , ...));
.
.
.

for(LatLng location : locations){
    mMap.addMarker(new MarkerOptions()
        .position(location)
        .title(...)
}

Problem

I've just started coding in android and after a very long time I got my google map to work and have been able to put markers on it. What I want to do next is create a array of latlng and use for loop to put a marker on the google maps. I cannot figure out how to do. Could someone please help me. I have done the following so far. ``` ArrayList<Markers> mMap = new ArrayList<Markers>(); public ArrayList arraylist[] = {new ArrayList( new LatLng(30.243442, -1.432320)), ``` I would like to expand this later, hence I would like to use array list. I understand how the for loop works, but I cannot work out how to implement it with this as I cannot get those locations from array to tag on my map. ``` for (i = 0; i < cars.length; i++) { mMap.addMarker(new MarkerOptions() .position(new LatLng(10, 10)) .title("Hello world")); } ``` I am completely lost from this stage. Could someone please guide and help me out. Thanks.

Original source