Updated 25 July 2020
Today, we will discuss about Marker clustering in swift on Google Maps.
lets small looks about the Marker cluster.
The marker clustering utility helps you to manage multiple markers at different zoom levels. When you view the map at a high zoom level it will show the individual markers on the map and when you zoom out it will show the markers gather together into clusters.
Google introduces Google-Maps-iOS-Utils library for easier to implement in the app. To read more details please visit Google Marker Cluster.
Swift version: 5
iOS version: 13
Xcode: 11.3
Step 1: Create a project from Xcode.
File ▸ New ▸ Project…. Choose the iOS ▸ Application ▸ Single View App template and create a new project.
Step 2: Install Google-Maps-iOS-Utils pod in the project.
1 |
pod 'Google-Maps-iOS-Utils' |
Step 3: Add UIView in our Viewcontroller and set the GMSMapView class for this view.
Note: You can create a view programmatically.
Step 4: Create an instance of GMUClusterManage and Pass the instance of GMSMapView you want to implement marker clustering.
Follow the below protocols to the GMUClusterManager instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@IBOutlet var mapView: GMSMapView! private var clusterManager: GMUClusterManager! override func viewDidLoad() { super.viewDidLoad() getOtherStoresList() let iconGenerator = GMUDefaultClusterIconGenerator() let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm() let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator) clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer) } |
Step 5: Now add markers in the cluster.
Two ways you can add a marker in the cluster.
First individually:
1 2 3 |
let position = CLLocationCoordinate2D(latitude: 28.60, longitude: 72.33) let marker = GMSMarker(position: position) clusterManager.addItem(marker) |
Second Array:
1 2 |
let markers = [GMSMarker1, GMSMarker2, GMSMarker3, GMSMarker4] clusterManager.add(markerArrays) |
Step 6: Now passed the markers to the cluster.
1 |
clusterManager.cluster() |
Great!! the code part has done. Now run the app.
I hope this code will help you better to understand Marker Cluster. If you feel any doubt or query please comment below.
Thank you.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.