1

我使用代码从谷歌方向api解析坐标和折线:

-(void)routeParser:(NSString *)sourceAddress andDestination:(NSString *)destinationAddress{
    NSLog(@"des sour %@",sourceAddress);
    NSError *error = nil;

    NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false", sourceAddress, destinationAddress];
    //&alternatives=true
    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
    NSLog(@"apiResponse %@",apiResponse);
    SBJsonParser *jsonParser = [SBJsonParser new];
    NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:apiResponse];
    NSLog(@"apiResponse is : %@",[jsonData objectForKey:@"routes"]);
    NSArray *routeArray = [[NSArray alloc]init];
    routeArray= [jsonData objectForKey:@"routes"];

    for(int i=0;i<[routeArray count];i++)
    {
        NSDictionary *tempDictionary = [routeArray objectAtIndex:i];
        if([tempDictionary objectForKey:@"overview_polyline"]!=nil)
        {
            NSDictionary *secTempDictionary = [tempDictionary objectForKey:@"overview_polyline"];
            if([secTempDictionary objectForKey:@"points"]!=nil)
            {
                NSString * routePoint =[secTempDictionary objectForKey:@"points"];

                [routeSetAry addObject:routePoint];

                encodedPoints = [secTempDictionary objectForKey:@"points"];
            }
            // NSLog(@"secTempDictionary is: %@", secTempDictionary);
        }
        if([tempDictionary objectForKey:@"legs"]!=nil)
        {
            NSArray *lagArray = [[NSArray alloc]init];
            lagArray= [tempDictionary objectForKey:@"legs"];

            for(int i=0;i<[lagArray count];i++)
            {
                NSDictionary *thirdTempDictionary = [lagArray objectAtIndex:i];
                if([thirdTempDictionary objectForKey:@"steps"]!=nil)
                {
                    NSArray *stepsArray = [[NSArray alloc]init];
                    stepsArray= [thirdTempDictionary objectForKey:@"steps"];

                    for(int i=0;i<[stepsArray count];i++)
                    {
                        NSDictionary *forthTempDictionary = [stepsArray objectAtIndex:i];

                        if([forthTempDictionary objectForKey:@"html_instructions"]!=nil)
                        {
                            NSString * directionStr =[forthTempDictionary objectForKey:@"html_instructions"];

                            NSRange range;
                            while ((range = [directionStr rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound){
                                directionStr=[directionStr stringByReplacingCharactersInRange:range withString:@""];
                            }
                            [directionStrAry addObject:directionStr];
                        }

                        NSDictionary *fifthTempDictionary = [forthTempDictionary objectForKey:@"polyline"];
                        if([fifthTempDictionary objectForKey:@"points"]!=nil)
                        {
                            NSString * routePoint =[fifthTempDictionary objectForKey:@"points"];

                            [polylineSetAry addObject:routePoint];

                            // encodedPoints = [fifthTempDictionary objectForKey:@"points"];
                        }
                        NSDictionary *sixthTempDictionary =[forthTempDictionary objectForKey:@"distance"];
                        if([sixthTempDictionary objectForKey:@"text"]!=nil)
                        {
                            NSString * distanceStr =[sixthTempDictionary objectForKey:@"text"];

                            [distanceStrAry addObject:distanceStr];

                            // encodedPoints = [fifthTempDictionary objectForKey:@"points"];
                        } 
                    }
                }
            }
        }  
    }

    NSLog(@"routeSetAry is :%@",routeSetAry);
    NSLog(@"polylineSetAry is : %i",polylineSetAry.count);

}

但问题是它在开始时记录 null 并返回 null apiResponse。我的错在哪里我无法理解,任何人帮助?

4

2 回答 2

0
- (void) getRoute
{
     polyline.map = nil;
     [googleMapView clear];
     NSString *strUrl = [NSString   stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?&alternatives=true&origin=%@&destination=%@&key=%@&sensor=false",self.sourceText.text,self.destnText.text,googleAPI_Key];

     [self routeDataUrl1:strUrl];
     [self.view addSubview:self.getInfo];
     [self.view addSubview:customIndicatorView]; 
}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
     if (webData) //webData is object of NSData
     {
         [self gettingData:webData ]; //calling the method gettingData
     }

     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
     webData=nil;
}

//after that gettingData method

- (void) gettingData:(NSData *)data
{

    NSDictionary *allDataDictionary = [NSJSONSerialization 
                                  JSONObjectWithData:data options:0 
                                  error:nil];

    if ([[NSString stringWithFormat:@"%@",[allDataDictionary objectForKey 
    : @"status"]] isEqualToString: @"OK"]) 

    {

        collectionArray =[[NSMutableArray alloc]init];
        NSMutableArray *legsArray = [[NSMutableArray alloc] initWithArray:allDataDictionary[@"routes"]];


        for (int i=0; i< [legsArray count]; i++)
        {

            [collectionArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:legsArray[i][@"legs"][0][@"distance"][@"text"],@"Distance", legsArray[i][@"legs"][0][@"duration"][@"text"],@"Duration",legsArray [i][@"summary"],@"Address",legsArray[i][@"legs"][0][@"summary"][@"html_instructions"][@"text"],@"HtmlInstructions",legsArray[i][@"overview_polyline"][@"points"],@"OverviewPolyline", nil]];
            [polyLineArray addObject:legsArray[i][@"legs"][0][@"steps"]];
            NSLog(@"11 == %@",legsArray[i][@"legs"][0][@"steps"]);         
        }    
        [self.getInfo reloadData];  //where getInfo is the TableView
    }
    else
    {
        NSString *msg=[allDataDictionary objectForKey:@"error_message"];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error !" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

        [alert show];
    }
}

希望这可以帮助你...

于 2016-02-23T05:10:06.000 回答
-1

Google is denying access through Client script. You need to handle that server side to download the json data and pass json result to client.

Update:

string Origin = "Chennai, Tamil Nadu, India"; string Destination = "Bangalore, Karnataka, India";

            var geojsonurl = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Origin  + "&destination=" + Destination + " &sensor=true";

            WebClient c = new WebClient();
            var json = c.DownloadString(geojsonurl);
            GoogleMapsRoutes data = JsonConvert.DeserializeObject<GoogleMapsRoutes>(json);

            StringBuilder Originstrlatlng = new StringBuilder();
            StringBuilder Deststrlatlng = new StringBuilder();

            if (!(data == null))
            {
                foreach (var item in data.routes[0].legs[0].steps)
            {
                Originstrlatlng.Append (item.start_location.lat.ToString() + "," + item.start_location.lng.ToString() + "|");
                Deststrlatlng.Append(item.end_location.lat.ToString() + "," + item.end_location.lng.ToString() + "|");
            }
            }


public class GoogleMapsRoutes
{
    public List<Route> routes { get; set; }
    public string status { get; set; }

}

public class Northeast
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Southwest
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Bounds
{
    public Northeast northeast { get; set; }
    public Southwest southwest { get; set; }
}

public class Distance
{
    public string text { get; set; }
    public int value { get; set; }
}

public class Duration
{
    public string text { get; set; }
    public int value { get; set; }
}

public class EndLocation
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class StartLocation
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Distance2
{
    public string text { get; set; }
    public int value { get; set; }
}

public class Duration2
{
    public string text { get; set; }
    public int value { get; set; }
}

public class EndLocation2
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Polyline
{
    public string points { get; set; }
}

public class StartLocation2
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Step
{
    public Distance2 distance { get; set; }
    public Duration2 duration { get; set; }
    public EndLocation2 end_location { get; set; }
    public string html_instructions { get; set; }
    public Polyline polyline { get; set; }
    public StartLocation2 start_location { get; set; }
    public string travel_mode { get; set; }
    public string maneuver { get; set; }
}

public class Leg
{
    public Distance distance { get; set; }
    public Duration duration { get; set; }
    public string end_address { get; set; }
    public EndLocation end_location { get; set; }
    public string start_address { get; set; }
    public StartLocation start_location { get; set; }
    public List<Step> steps { get; set; }
    public List<object> via_waypoint { get; set; }
}

public class OverviewPolyline
{
    public string points { get; set; }
}

public class Route
{
    public Bounds bounds { get; set; }
    public string copyrights { get; set; }
    public List<Leg> legs { get; set; }
    public OverviewPolyline overview_polyline { get; set; }
    public string summary { get; set; }
    public List<object> warnings { get; set; }
    public List<object> waypoint_order { get; set; }
}

This works. just try.

于 2013-11-11T05:36:37.960 回答