我正在尝试从geo json文件在Google地图上绘制多边形。我知道如何从很少的坐标绘制路径,但是我无法从Google地图绘制
这是我的JSON文件
{
"type": "Polygon",
"coordinates": [
[
[
90.35087585449219,
23.87767555995429
],
[
90.35293579101562,
23.877832529038052
],
[
90.45867919921875,
23.662449542924175
],
[
90.45455932617188,
23.66103447347277
],
[
90.35053253173828,
23.872966398925893
],
[
90.35018920898438,
23.87516402872517
],
[
90.35087585449219,
23.87767555995429
]
]
]
}
如何从此json绘制多边形? 我也希望Google地图使用动态方式而不是静态方式
谢谢
答案 0 :(得分:0)
解析并创建CLLLocation2D数组,然后在该数组中添加所有坐标;
let polygon = MKPolygon(coordinates: yourArray, count: yourArray.count)
yourMapView.addOverlay(polygon)
创建前请检查,坐标的第一个元素应与坐标的最后一个元素相同。
通过我假设您已经扩展了视图控制器并添加以下方法的方式。如果您没有扩展,请写下扩展并委托自我。
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolygonRenderer(overlay: overlay)
renderer.lineWidth = 5 //Customize as you wish
renderer.fillColor = .green
renderer.strokeColor = .red
return renderer
}
答案 1 :(得分:0)
尝试这种方式可能会有所帮助:)
struct ResponseData: Decodable {
var coordinates: [coordinates]
var type : String
}
struct coordinates : Decodable {
var lng: String
var lat: String
}
创建2个结构
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
let path = GMSMutablePath()
if let url = Bundle.main.url(forResource: "document", withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(ResponseData.self, from: data)
for te in jsonData.coordinates {
path.add(CLLocationCoordinate2D(latitude: te.lat.toDouble(), longitude: te.lng.toDouble()))
}
}
catch {
//Handle error
print(error.localizedDescription)
}
}
let rectangle = GMSPolyline(path: path)
rectangle.strokeColor = .red
rectangle.strokeWidth = 5.0
rectangle.map = mapView
}