The Open Event Android project helps event organizers to generate Apps (apk format) for their events/conferences by providing API endpoint or zip generated using Open Event server. In the Open Event Android App, we have a map for showing all locations of sessions. In this map users should be able to see different locations with multiple markers. In this post I explain how to add multiple markers in the Google map fragment and set the bound in the map so that all markers are visible on one screen with specified padding.
Create Map Fragment
The first step to do is to create a simple xml file and add a fragment element in it. Then create MapsFragment.java file and find fragment element added in the xml file using findFragmentById() method.
1. Create fragment_map.xml file
In this file add FrameLayout as a top level element and add fragment element inside FrameLayout with the name “com.google.android.gms.maps.SupportMapFragment”.
2. Create MapsFragment.java
MapsFragment.java extends SupportMapFragement and implements LocationListener, OnMapReadyCallback. Make instance of GoogleMap object. In onViewCreated method inflate fragment_map.xml file using inflater. Now find the fragment element added in the xml file using findFragmentById() method and assign it to SupportMapFragement instance.
Create list of locations
Location object has three variables name, latitude & longitude. Create a list of locations for which we want to add markers to the map.
Add location objects in mLocations in onViewCreated() method
You can add multiple locations using for loop or fetching from the database.
Add following code in onMapReady(GoogleMap map) method. onMapReady(GoogleMap map) is called when map is ready to be used. setMapToolbarEnabled(true) used to show toolbar for marker. If the toolbar is enabled users will see a bar with various context-dependent actions, including ‘open this map in the Google Maps app’ and ‘find directions to the highlighted marker in the Google Maps app’.
Create showEventLocationOnMap() method and add following code
So what we are doing here?
For each location object in mLocations list, we are creating LatLng(latitude, longitude) object and adding it to the map using
We want to set the zoom level so that all markers are visible. To do this, we can use LatLngBounds.Builder. Add the position of the marker in the builder object using include method while adding the marker in the map.
Then make the LatLngBounds object from builder.
dpTopx converts dp to px so that it set the same padding in all devices.
Markers in map give very nice user experience for an event or a conference because they show the relative position of places and we now offer this feature in Open Event Android.