Search code examples
iosgoogle-mapsmkmapview

How to calculate actual road distance on mkmapview?


I have calculated distance between 2 points(latitude and longitude). I used distanceFromLocation: but this gives me aerial distance. I have drawn MKPolyline on MKMapview showing road route. Now the problem is that, how can i get the actual road distance without using GOOGLE API?


Solution

  • I got my answer which gives me actual distance.

    - (NSArray*)getRoutePointFrom:(myannotation *)origin to:(myannotation *)destination 
    {
        NSString* sourcePoint = [NSString stringWithFormat:@"%f,%f",origin.coordinate.latitude, origin.coordinate.longitude];
        NSString* destinationPoint = [NSString stringWithFormat:@"%f,%f", destination.coordinate.latitude, destination.coordinate.longitude];
    
        NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@", sourcePoint, destinationPoint];
        NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
    
        NSError *error;//saddr
        NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:&error];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"points:\"([^\"]*)\"" options:0 error:NULL];
        NSTextCheckingResult *match = [regex firstMatchInString:apiResponse options:0 range:NSMakeRange(0, [apiResponse length])];
        NSString *encodedPoints = [apiResponse substringWithRange:[match rangeAtIndex:1]];
    
        NSRegularExpression *distRegEx=[NSRegularExpression regularExpressionWithPattern:@"tooltipHtml:\"([^\"]*)\""options:0 error:NULL];
        NSTextCheckingResult *distmatch=[tempregx firstMatchInString:apiResponse options:0 range:NSMakeRange(0, [apiResponse length])];
    
        NSString *dist= [apiResponse substringWithRange:[temppmatch rangeAtIndex:0]];
        NSLog(@"dist in Km: %@",dist);
        return [self decodePolyLine:[encodedPoints mutableCopy]];
      }