如何在没有连接的情况下在MapView上绘制两个MKPolygon?

问题描述 投票:0回答:2

出于某种原因,当我尝试在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()
    }
swift xcode mkmapview mkpolygon
2个回答
0
投票

似乎您正在制作由[[two多边形组成的one叠加层。您不能使用MKPolygonRenderer来做到这一点;您将观察到一个多边形。

您将需要单独的叠加层,每个多边形一个。除非您使用的是iOS 13!在这种情况下,您很幸运:iOS 13中的新增功能,可以将多个多边形或折线合并到MKMultiPolygon或MKMultiPolyline中,并通过MKMultiPolygonRenderer或MKMultiPolylineRenderer进行绘制。

0
投票
我忘记检查/发布正在调用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试图最好在它们之间形成一个多边形。

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

© www.soinside.com 2019 - 2024. All rights reserved.