从Json解析经度和经度到我的应用程序

时间:2013-12-15 13:34:56

标签: json google-maps parsing ios7

我正在尝试将我的Json结果插入到我的项目中

我有以下地图为我的位置设置了一个带有2个指针和第3个指针的运行:

//create a marker for Car

GMSMarker *marker2 = [[GMSMarker alloc] init];
marker2.position = CLLocationCoordinate2DMake(+51.7849979425945, -1.485403844654244);

// change colour to green
UIColor *green;
green =[UIColor greenColor];
marker2.icon =[GMSMarker markerImageWithColor:green];

 }

我也从以下代码中获取数据

 // WHEN VIEWCONTROLLER LOADS
- (void)viewDidLoad
{

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[super viewDidLoad];

NSURL *url =[NSURL URLWithString:@"http://www.dmk-media.com/taxi/json.php"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
 (void) [[NSURLConnection alloc]initWithRequest:request delegate:self]; }

如果你去网址,你会看到只返回一行Json

的数据
 [{"ID":"2","Longitude":"-1.485662152530882","Lat":"51.7847928765227","Date":"2013-12-13 22:46:15"}]

我需要知道的是如何从Json结果获得经度和纬度

marker2.position = CLLocationCoordinate2DMake(+51.7849979425945, -1.485403844654244);

我尝试了各种各样的帮助和示例,但我一直在打砖墙我已经在这一段时间了,请帮助

1 个答案:

答案 0 :(得分:0)

更新: 为了使用lat和long out side那个方法做到这一点: 在你的.h文件中:

@property(nonatomic,strong)NSString *lat;
@property(nonatomic,strong)NSString *longi;

并在你的.m文件中同步这些变量并在void连接方法中(现在参见更新的函数)。

您必须从json格式解析数据,以便您可以将响应保存在nsdicitionary中,而不是能够针对每个键读取值。请遵循此示例。

-(void)fetchData{
    NSURL *url =[NSURL URLWithString:@"http://www.dmk-media.com/taxi/json.php"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    NSURLConnection *conn=[[NSURLConnection alloc]initWithRequest:request delegate:self];

    [conn start];

}

新更新:用于设置marker2.position

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSError *error;
    NSArray* results = [NSJSONSerialization JSONObjectWithData:data
                                                       options:0
                                                         error:&error];
    NSDictionary *responseValues=[results objectAtIndex:0];
    NSLog(@"the resposne is %@",responseValues);
    lat=[responseValues objectForKey:@"Lat"];
   longi=[responseValues objectForKey:@"Longitude"];
   [self setMarkerPosition];

}
-(void)setMarkerPosition{
GMSMarker *marker2 = [[GMSMarker alloc] init];
marker2.position = CLLocationCoordinate2DMake(lat.FloatValue, longi.FloatValue);

// change colour to green
UIColor *green;
green =[UIColor greenColor];
marker2.icon =[GMSMarker markerImageWithColor:green];

}

您还必须在.h文件中包含此行。

UIViewController<NSURLConnectionDelegate,NSURLConnectionDataDelegate> 

我创建了我在viewdidload方法中调用的fetchData函数。