首页 > 解决方案 > 在 Google 地图上显示多个“GMSMarker”标记

问题描述

我正在尝试使用谷歌地图显示多个位置,代码只显示一个位置。我正在使用 for 循环。我使用 MKMapView 检查了代码,它正在工作。

这是代码:

let dict = [self.jsonElement]

            for dicts in dict {

                let latiCon = (dicts.value(forKey: "lati") as! NSString).doubleValue
                let longiCon = (dicts.value(forKey: "longi") as! NSString).doubleValue

            // Create a GMSCameraPosition that tells the map to display the
            // coordinate -33.86,151.20 at zoom level 6.
            let camera = GMSCameraPosition.camera(withLatitude: latiCon, longitude: longiCon, zoom: 6.0)
            let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
            self.view = mapView

            // Creates a marker in the center of the map.
            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude: latiCon, longitude: longiCon)
            marker.title = "Sydney"
            marker.snippet = "Australia"
            marker.map = mapView

            }

正如我所说,我需要显示多个位置,我查看了相关答案,但没有找到与我的问题匹配的任何内容。

标签: swiftgoogle-maps

解决方案


这段代码

 let camera = GMSCameraPosition.camera(withLatitude: latiCon, longitude: longiCon, zoom: 6.0)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        self.view = mapView

每次循环制作一个新的mapView,所以你得到的很自然。一个新的地图视图 + 一个标记。如果您之前已经声明了 mapview,则将此代码移到循环之外或将其删除。


推荐阅读