如何在不连接的情况下在 MapView 上绘制两个 MKPolygons?

How can I draw two MKPolygons on MapView without having them connect?

出于某种原因,当我尝试在 mapView (MKMapView) 上绘制两个 MKPolygons 时,我最终连接了两个多边形。单独绘制每个多边形效果很好。而且我已经验证每个多边形都不包含任何坐标来形成两者之间的连接。 I've attached an image with the two polygons connected

作为参考,这里是我调用添加多边形的地方。

func addPeakTimePolygon(from coordinatesArray: [CLLocationCoordinate2D], title: Int){
            let polygon = MKPolygon(coordinates: coordinatesArray, count: coordinatesArray.count)
            polygon.title = String(title)
            //Should refactor to use .contains(where:
            var shouldAdd = true
            for polygon in self.currentPolygons{
                if polygon.title == String(title){
                    shouldAdd = false
                }
            }
            if shouldAdd{
                self.currentPolygons.append(polygon)
                self.mapView.add(polygon)
            }
    } 

这是我的 rendererFor 代码:

 func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay is MKPolyline {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = #colorLiteral(red: 0, green: 0.6862745098, blue: 0.7607843137, alpha: 1)
            renderer.lineWidth = 5.0
            return renderer
        }
        else if overlay is MKPolygon {
            let renderer = MKPolygonRenderer(overlay: overlay)
            renderer.fillColor = UIColor.red.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.red
            renderer.lineWidth = 2
            return renderer
        }
        return MKOverlayRenderer()
    }

您似乎正在制作由 两个 多边形组成的 一个 叠加层。你不能用 MKPolygonRenderer 做到这一点;正如您观察到的那样,您将得到一个多边形。

您将需要单独的叠加层,每个多边形一个。除非你用的是iOS13!在那种情况下,你很幸运: iOS 13 中的新功能,多个多边形或折线可以组合成 MKMultiPolygon 或 MKMultiPolyline 并由 MKMultiPolygonRenderer 或 MKMultiPolylineRenderer 绘制。

我忘记检查/post 调用 addPeakTimePolygon 的代码。下面是有问题的代码:

var locationList: [CLLocationCoordinate2D] = []
        var title = 0
        if let peakTimeCampaignList = data["PeakTimeRewardCampaignList"] as? [[AnyHashable:Any]]{
            for campaign in peakTimeCampaignList{
                if let polygonPoints = campaign["CampaignPolygon"] as? [[AnyHashable:Any]]{
                    for polygonPoint in polygonPoints{
                        let polygonPoint = CLLocationCoordinate2D(latitude: polygonPoint["Latitude"] as! CLLocationDegrees, longitude: polygonPoint["Longitude"] as! CLLocationDegrees)
                        locationList.append(polygonPoint)
                    }
                }
                if let id = campaign["Id"] as? Int{
                    title = id
                }
                mapBundle.addPeakTimePolygon(from: locationList, title: title)
            }
        }

如您所见,locationList 没有在循环中被清除,导致我们发送到 addPeakTimePolygon 的任何内容都具有来自两个多边形的坐标,而 MapKit 正在尝试最好形成一个它们之间的多边形。

这是一个愚蠢的错误,但希望其他人看到同样的问题!