如何在Swift的Google Map中使用“群集”对标记进行分组?

时间:2018-08-16 07:22:39

标签: swift google-maps

我构建的应用程序具有Google Map功能。如何使用群集将标记分组(您可以看到图像)。有人告诉我怎么做吗?非常感谢

my marker

enter image description here

3 个答案:

答案 0 :(得分:1)

首先,您需要按以下方式初始化集群管理器对象,这将通过viewDidLoad方法进行调用。

// MARK: INITIALIZE CLUSTER ITEMS
func initializeClusterItems() {
    let iconGenerator = GMUDefaultClusterIconGenerator()
    let algorithm = GMUGridBasedClusterAlgorithm()
    let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator)
    self.clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer)
    self.clusterManager.cluster()
    self.clusterManager.setDelegate(self as GMUClusterManagerDelegate, mapDelegate: self)
}

然后更新您的代码

func setMarkerForMap(locations: [LocationNearBy]) -> Void {

    let imgTypeDoctor = UIImage(named: "map_icon_doctor")
    let imgTypeHospital = UIImage(named: "map_icon_hospital")
    let imgTypeDrugstore = UIImage(named: "map_icon_medicin")

    //clear all marker before load again
    self.mapView.clear()
    var index = 0
    for location in locations {

        let marker = GMSMarker()
        let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(location.lat), longitude: CLLocationDegrees(location.long))
        marker.position = coordinate

        //set image
        if (location.locationTypeID == 1) {
            marker.icon = imgTypeDoctor
        } else if (location.locationTypeID == 2 || location.locationTypeID == 3 || location.locationTypeID == 4) {
            marker.icon = imgTypeHospital
        } else if (location.locationTypeID == 5) {
            marker.icon = imgTypeDrugstore
        }

        marker.userData = location
        marker.map = mapView
        mapView.delegate = self
        self.generatePOIItems(String(format: "%d", markerIndex), position: coordinate, icon: marker.icon)
       index += 1
    }
    self.clusterManager.cluster()
}

然后我们必须将标记分配给clusterManager对象

// MARK: ADD MARKER TO CLUSTER
func generatePOIItems(_ accessibilityLabel: String, position: CLLocationCoordinate2D, icon: UIImage?) {
    guard let item = POIItem(position: position, name: accessibilityLabel, icon: icon) else {
        return
    }
    self.clusterManager.add(item)
}

希望这会对您有所帮助。

答案 1 :(得分:0)

 func setMarkerForMap(locations: [LocationNearBy]) -> Void {

        //clear all marker before load again
        self.mapView.clear()

        let location = locations[0]
        let update = GMSCameraUpdate.setTarget(CLLocationCoordinate2D(latitude: CLLocationDegrees(location.lat), longitude: CLLocationDegrees(location.long)), zoom: 10)

        for location in locations {

            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(location.lat), longitude: CLLocationDegrees(location.long))

            //set image
            if (location.locationTypeID == 1) {
                marker.icon = UIImage(named: "map_icon_doctor")
            } else if (location.locationTypeID == 2 || location.locationTypeID == 3 || location.locationTypeID == 4) {
                marker.icon = UIImage(named: "map_icon_hospital")
            } else if (location.locationTypeID == 5) {
                marker.icon = UIImage(named: "map_icon_medicin")
            }

            marker.userData = location
            marker.map = mapView
            marker.tracksInfoWindowChanges = true
            mapView.delegate = self
        }
        mapView.animate(with: update)
    }

答案 2 :(得分:0)

class POIItem: NSObject, GMUClusterItem {
var position: CLLocationCoordinate2D
var name: String!
var icon: UIImage

  init(position: CLLocationCoordinate2D, name: String, icon: UIImage) {
    self.position = position
    self.name = name
    self.icon = icon
  }
}

class HomeViewController: UIViewController {
//MARK:- Variable 
private var clusterManager: GMUClusterManager!

override func viewDidLoad(){
let iconGenerator = GMUDefaultClusterIconGenerator()
let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
let renderer = GMUDefaultClusterRenderer(mapView: self.mapView ?? GMSMapView(),clusterIconGenerator: iconGenerator)
renderer.delegate = self
self.clusterManager = GMUClusterManager(map: self.mapView ?? GMSMapView(), algorithm: algorithm,
                                                    renderer: renderer)


self.clusterManager.setDelegate(self, mapDelegate: self)
// Call cluster() after items have been added to perform the clustering and rendering on map.
self.clusterManager.cluster()

for i in 0..<self.model.count{
     //if you want to rescale image of marker. function used imageWithImage()           
     let img = self.imageWithImage(image: #imageLiteral(resourceName: "imgMarker"), scaledToSize: CGSize(width: 60, height: 35))

  // Generate and add random items to the cluster manager.
     self.generateClusterItems(lat: self.model[i].lat ?? "", lng: self.model[i].long ?? "", name: "\(i)", icon: img)
   }
}

/// Randomly generates cluster items within some extent of the camera and
/// adds them to the cluster manager.
private func generateClusterItems(lat: String, lng: String,name: String, icon: UIImage) {
    let lat = JSON(lat).doubleValue
    let lng = JSON(lng).doubleValue
    let item =
        POIItem(position: CLLocationCoordinate2DMake(lat, lng), name: name, icon: icon)

    clusterManager.add(item)
}

///function to make image rescaled
func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
  }
}

 //MARK:- GMUClusterManagerDelegate-
extension HomeViewController: GMUClusterManagerDelegate {
func clusterManager(_ clusterManager: GMUClusterManager, didTap clusterItem: GMUClusterItem) -> Bool {
    print("didTap clusterItem")    
    return true
}

func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
    print("didTap cluster")
    return true
 }
}