簡體   English   中英

iOS-如何從JSON文件中創建與其GMSMutablePath關聯的GMSPolygons字典

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM