1

嗨,我有一个服务器 json 格式的文件,其中包含几个地图点:

["VALUE","proyect",[{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]]

我想在我的 ios 应用程序中将这些点作为标记放在我的地图上。我已经查看了几页和这里,但我没有找到任何东西,而且我尝试过的方法不起作用。

请问有什么帮助吗?

4

2 回答 2

2

首先,您首先解析您的 JSON:

NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSAssert(array, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

其次,您可以从该顶级数组中获取位置数组,为该数组中的每个位置字典创建注释,并将其添加到您的地图中:

// the array of locations is the third object in the top-level array

NSArray *locations = array[2];

// now iterate through this array of locations

for (NSDictionary *location in locations)
{
    // grab the latitude and longitude strings

    NSString *latitudeString = location[@"lat"];
    NSAssert(latitudeString, @"No latitude");
    NSString *longitudeString = location[@"lng"];
    NSAssert(longitudeString, @"No longitude");

    // create the annotation and add it to the map

    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
    annotation.coordinate = CLLocationCoordinate2DMake([latitudeString doubleValue], [longitudeString doubleValue]);
    annotation.title = location[@"name"];
    annotation.subtitle = location[@"address"];
    [self.mapView addAnnotation:annotation];
}

话虽如此,我必须说我不关心 JSON 格式:

["VALUE","proyect",[{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]]

对于我们来说,必须猜测这个数组中的第一个、第二个和第三个对象是什么,这是一个值得怀疑的设计。我们不必神秘地抓取array[2]来获取位置数组。

数组应该用于等价项目的列表(例如,位置数组非常有意义)。但是这个顶级数组有点可疑,具有三种语义上非常不同的值类型,JSON 中没有任何内容可以指示这三个项是什么。

如果您坚持使用这种 JSON 格式,那么,很好,上面的代码应该可以完成这项工作。但希望您可以将此处的顶级结构更改为字典,而不是数组,您可以在其中使用键名来标识此顶级字典中的各种项目,例如:

{"id" : "VALUE", "project" : "proyect", "locations" : [{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]}

我不知道前两个值应该是什么,所以我只称它们为idand project,但您显然应该使用真正反映前两个值的名称。但关键概念是使用字典,您可以在其中按名称引用位置数组。例如,如果 JSON 像我在这里建议的那样更改,则解析它的代码将变为:

NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSAssert(dictionary, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

NSArray *locations = dictionary[@"locations"];

此外,作为一种风格观察,许多人通常会将纬度和经度值表示为数字(不带引号),并将NSJSONSerialization它们解析为NSNumber对象而不是NSString对象。但这取决于你。

于 2014-01-04T17:57:06.760 回答
1

您需要解析 JSON 以检索每个点的数据,然后为每个点创建一个您自己的 MKMapViewAnnotation 实例并将它们添加到地图中。

更多信息在这里: http: //maybelost.com/2011/01/a-basic-mapview-and-annotation-tutorial/

在这里:如何在 MKMapView 上添加地图注释?

有关在此处解析 JSON 的信息:http: //www.appcoda.com/fetch-parse-json-ios-programming-tutorial/

于 2014-01-04T16:56:28.183 回答