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
}
})
}
A solution depends on your requirements. If it is required that the center is within the polygon, the solution provided by Paul van Roosendaal is perfect.
However, in many cases it is better if the center can also be outside of the polygon. Think, e.g. of a polygon that looks like a nearly closed ring. In this case, it may be more natural that the center is roughly in the center of the ring, and the center is computed as the centroid of the polygon.
In the cited wiki post, this reference discusses how to compute it, and shows a number of implementations in different languages.
I have translated the Java version into Swift, and added an example: