Search code examples
androidgoogle-mapsgoogle-maps-markersgoogle-maps-api-2

Adding multiple markers in Google Maps API v2 Android


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?


Solution

  • 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)));
    }