简体   繁体   中英

The Google Distance Matrix APi (JSON PARSING)

i am new programmer. and i am using Google Distance Matrix API. I am first time using JSON . i use the Following but can't get response from server.. please give me few lines code for use JSON and fetch the distance in kilometer between two places.

http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false

Thanks

when i use the following API i receive the response

- (void)viewDidLoad  {

    [super viewDidLoad]; 

    NSLog(@"viewdidload");
    responseData = [[NSMutableData data] retain]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

  }

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{

    NSLog(@"didReceiveResponse");
   [responseData setLength:0];

  }

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

 {        
    [responseData appendData:data]; 
 }

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{    
    NSLog(@"didFailWithError");
    label.text = [NSString stringWithFormat:@"Connection failed: %@",
                                            [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

 {
    NSLog(@"connectionDidFinishLoading");   
    NSString* newStr = [[NSString alloc] initWithData:receivedData
                                             encoding:NSUTF8StringEncoding];
    [self handleResponce:newStr];
   // NSLog(@"%@",newStr);
 }

-(void)handleResponce:(NSString *)data

{
    NSLog(@"receive data is --------->%@",receiveData);
}

Try to use this API instead : afGoogleMapsAPI-WS-iOS

How to use

afGMapsDistanceRequest *req = [afGMapsDistanceRequest distanceRequest];

req.afDelegate = self;

NSMutableArray *orAr = [NSMutableArray array];

[orAr addObject:@"Paris"];
[orAr addObject:@"Berlin"];

NSMutableArray *deAr = [NSMutableArray array];

[deAr addObject:@"Marseille"];
[deAr addObject:@"Barcelone"];

[req setOrigins:orAr];

[req setDestinations:deAr];

[req setUseSensor:YES];
[req setUseHTTPS:NO];

[req setAvoidMode:AvoidModeTolls]; //optional, none default

[req setUnitsSystem:UnitsMetric]; //optional, metrics default

[req setTravelMode:TravelModeDriving]; //optional, driving default

[req startAsynchronous];

Then, simply make your class inherit the afGoogleMapsDistanceDelegate protocol, and implement the following delegate functions (if needed, all optional):

 -(void) afDistanceWSStarted:(afGMapsDistanceRequest *)ws ;

 -(void) afDistanceWS:(afGMapsDistanceRequest *)ws gotDistance:(NSNumber *) distance unit:(UnitsSystem)unit;

 -(void) afDistanceWSFailed:(afGMapsDistanceRequest *)ws withError:(NSString *)er;

 -(void) afDistanceWS:(afGMapsDistanceRequest *)ws origin:(NSString *) origin destination:(NSString *)destination failedWithError:(NSError *) err;

 -(void) afDistanceWS:(afGMapsDistanceRequest *)ws distance:(NSNumber *) distance origin:(NSString *) origin destination:(NSString *)destination unit:(UnitsSystem)unit;
This request will give you all the informations availbale. Variables called "returnedXXX" like "returnedDest" are the returned descriptions of GoogleMaps API WS.

 -(void) afDistanceWS:(afGMapsDistanceRequest *)ws distance:(NSNumber *) distance textDistance:(NSString *)textDistance origin:(NSString *) origin returnedOrigin:(NSString *)returnedOrigin destination:(NSString *)destination returnedDestination:(NSString *)returnedDest duration:(NSNumber *)durationInSec textDuration:(NSString *)textDuration unit:(UnitsSystem)unit;

What exactly is your problem?

  • Fetching the data?
  • Or parsing the JSON?
-(void)viewDidLoad{
    [super viewDidLoad];
    NSLog(@"viewdidload");  
    responseData = [[NSMutableData alloc] init];  
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC%7CSeattle&destinations=San+Francisco%7CVictoria+BC&mode=bicycling&language=fr-FR&sensor=false"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    [responseData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"connectionDidFinishLoading");
    NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [self handleResponse:newStr]; // NSLog(@"%@",newStr);
}
-(void)handleResponse:(NSString *)string{
    NSLog(@"responseData data is --------->%@",string);
}

Try this. You sometimes referred to responceData, and sometimes to receiveData. I fixed that and the name of the method. Plus you were trying to log the responseData and not the String.

I use the TouchJSON library available here

https://github.com/TouchCode/TouchJSON

to do something alone the lines of:

// For the purpose of this example, use stringWithContentsOfURL
NSString *googleURL = @"http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false";

NSURL *url = [NSURL
              URLWithString:[googleURL
                             stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSError *error = NULL;
NSString *theJSONString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

NSLog(@"%@", theJSONString);

// Parse with TouchJSON
NSDictionary *replyDict = [NSDictionary dictionaryWithJSONString:theJSONString error:&error];

NSString *distanceString = [[[[[[replyDict objectForKey:@"rows"] objectAtIndex:0]
                               objectForKey:@"elements"]
                              objectAtIndex:0]
                             objectForKey:@"distance"]
                            objectForKey:@"value"];

double distance = distanceString.doubleValue;

NSLog(@"Distance: %f", distance);
NSLog(@"Error: [%@]", error.description);

and that gives me the following output on the console:

{
   "destination_addresses" : [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
   "origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1 686 km",
                  "value" : 1685690
               },
               "duration" : {
                  "text" : "3 jours 21 heures",
                  "value" : 336418
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "136 km",
                  "value" : 136478
               },
               "duration" : {
                  "text" : "6 heures 59 minutes",
                  "value" : 25117
               },
               "status" : "OK"
            }
         ]
      },
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1 426 km",
                  "value" : 1426087
               },
               "duration" : {
                  "text" : "3 jours 6 heures",
                  "value" : 281311
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "251 km",
                  "value" : 251174
               },
               "duration" : {
                  "text" : "12 heures 6 minutes",
                  "value" : 43583
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
Distance: 1685690.000000
Error: [(null)]

If you want to use SBJson instead you can get it here

https://github.com/stig/json-framework

replace the line

// Parse with TouchJSON
NSDictionary *replyDict = [NSDictionary dictionaryWithJSONString:theJSONString error:&error];

with

// Parse with SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *replyDict = [parser objectWithString:theJSONString];

Remember to include the relevant library in your .h file

Hi Gaurav,

i tried this for your given URL response.

For getting proper tree structure visit this.

please check this code.

try this in didReceiveData delegate method

 NSString *serverOutput = [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease];
    SBJSON *parser = [[SBJSON alloc] init];

    // Get all data using this dic :) ;) text content twits.

    NSDictionary *dic = [parser objectWithString:serverOutput error:nil];
    NSLog(@"Response Dictionary ::: %@",dic);

    NSLog(@"Distance ::: %@",[[[[dic valueForKey:@"rows"] valueForKey:@"elements"] valueForKey:@"distance"] valueForKey:@"value"]);

hope this one is help flu to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM