[英]iOS - How to create a Dictionary of GMSPolygons associated with their GMSMutablePath from JSON file
我目前正在使用iOS Google Map SDK
,並且想在地圖上繪制一些多邊形。
更准確地說,我有一個JSON,其中包含特定部門的不同經度/緯度點。
我能畫一個GMSPolygon
通過創建GMSMutablePath
只有幾個百分點,由像谷歌文檔介紹。
另一方面,我無法實現的是使其通用。
讓我給你看一些代碼。
{"01": [[51.01, 2.07], [50.99, 2.12], [51.01, 2.11], [51.03, 2.15], ...], "02": [[50.51, 1.64], [50.51, 1.66], ...]}
我有這個JSON文件,其中包含特定部門的數千個職位點。 我將其縮短,以便您只能看到JSON對象的格式。
這是我的解析:
-(void) parseJsonDept {
NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"dept" ofType:@"json"];
if (!jsonFilePath) {
NSLog(@"Not a valid FilePath");
return;
}
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:jsonFilePath encoding:NSUTF8StringEncoding error:NULL];
if (!myJSON) {
NSLog(@"File couldn't be read!");
return;
}
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
}
非常簡單,現在我不知道如何處理。
我具有Google文檔中的這段代碼,以便繪制多邊形。
-(void) drawPolygon {
// Create a rectangular path
GMSMutablePath *rect = [GMSMutablePath path];
[rect addCoordinate:CLLocationCoordinate2DMake(51.01, 2.07)];
[rect addCoordinate:CLLocationCoordinate2DMake(50.99, 2.12)];
[rect addCoordinate:CLLocationCoordinate2DMake(51.03, 2.15)];
[rect addCoordinate:CLLocationCoordinate2DMake(51.01, 2.18)];
// Create the polygon, and assign it to the map.
GMSPolygon *polygon = [GMSPolygon polygonWithPath:rect];
polygon.fillColor = [UIColor colorWithRed:0.25 green:0 blue:0 alpha:0.05];
polygon.strokeColor = [UIColor blackColor];
polygon.strokeWidth = 2;
polygon.map = _mapView;
}
我的問題是如何創造的字典GMSPolygons
關聯到他們GMSMutablePath
和他們Department
。
例如,循環從我的JSON字典拋出每個部門,然后[rect addCoordinate:CLLocationCoordinate2DMake(lat, long)]
向我的GMSMutablePath
添加坐標。
依次類推每個部門,以便最終獲得多邊形列表。
我在JSON方面的工作超出了我的預期...
獲得Dictionary
您可以遍歷它並從中創建GMSMutablePath
。
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
GMSMutablePath *rect = [GMSMutablePath path];
for(id key in json) {
NSArray *coordinates = [json objectForKey:key];
for(NSArray *coordinate in coordinates) {
double latitude = [[coordinate firstObject] doubleValue];
double longitude = [[coordinate lastObject] doubleValue];
[rect addCoordinate:CLLocationCoordinate2DMake(latitude, longitude)];
}
}
// Create the polygon, and assign it to the map.
GMSPolygon *polygon = [GMSPolygon polygonWithPath:rect];
polygon.fillColor = [UIColor colorWithRed:0.25 green:0 blue:0 alpha:0.05];
polygon.strokeColor = [UIColor blackColor];
polygon.strokeWidth = 2;
polygon.map = _mapView;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.