I'm using iOS Mapbox
SDK and I need to find the center coordinate in a polygon because I want to add a marker in the center coordinate. How can I do this in Swift?
func drawPolygonFeature(shapes: [MGLShape & MGLFeature]) {
let shapeSource = MGLShapeSource(identifier: "MultiPolygonShapeSource", shapes: shapes, options: nil)
let lineStyleLayer = MGLLineStyleLayer(identifier: "LineStyleLayer", source: shapeSource)
lineStyleLayer.lineColor = NSExpression(forConstantValue: UIColor.purple)
lineStyleLayer.lineOpacity = NSExpression(forConstantValue: 0.5)
lineStyleLayer.lineWidth = NSExpression(forConstantValue: 4)
DispatchQueue.main.async(execute: {[weak self] in
guard let self = self else { return }
self.mapView.style?.addSource(shapeSource)
self.mapView.style?.addLayer(lineStyleLayer)
let multiPolygonFeature = shapes.first as? MGLMultiPolygonFeature
if let centerCoordinate = multiPolygonFeature?.polygons.first?.coordinate {
self.mapView.centerCoordinate = centerCoordinate
// but centerCoordinate var does not contain the center coordinate
}
})
}