Adding multiple markers in Google Maps API v2 Android

Tárraga picture Tárraga · Jun 1, 2015 · Viewed 78.1k times · Source

I want to add multiple markers in my map, but I don't know the way.

At the moment, I'm using this, and it works correctly:

Marker m1 = googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(38.609556, -1.139637))
                .anchor(0.5f, 0.5f)
                .title("Title1")
                .snippet("Snippet1")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.logo1)));


Marker m2 = googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(40.4272414,-3.7020037))
                .anchor(0.5f, 0.5f)
                .title("Title2")
                .snippet("Snippet2")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.logo2)));

Marker m3 = googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(43.2568193,-2.9225534))
                .anchor(0.5f, 0.5f)
                .title("Title3")
                .snippet("Snippet3")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.logo3)));

But the problem comes when I want to add 300 markers in my map. And doing it one by one is very annoying.

Is there any way to read markers from array or anything?

Another question: could I read markers from external file, so I can add or update markers without touching app code?

Answer

nbaroz picture nbaroz · Jun 1, 2015
ArrayList<MarkerData> markersArray = new ArrayList<MarkerData>();

for(int i = 0 ; i < markersArray.size() ; i++) {

    createMarker(markersArray.get(i).getLatitude(), markersArray.get(i).getLongitude(), markersArray.get(i).getTitle(), markersArray.get(i).getSnippet(), markersArray.get(i).getIconResID());
}


protected Marker createMarker(double latitude, double longitude, String title, String snippet, int iconResID) {

    return googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .anchor(0.5f, 0.5f)
            .title(title)
            .snippet(snippet)
            .icon(BitmapDescriptorFactory.fromResource(iconResID)));
}