在iPhone上的谷歌地图上绘制路线

时间:2012-04-12 07:25:54

标签: iphone ios

我想使用纬度和经度在mapview上绘制路线。怎么可能画画?

这是我的代码。但它不起作用。我已经在点可变阵列中添加了位置。之后调用drawRoute函数在该位置之间绘制路径。

- (void)viewDidLoad {
    [super viewDidLoad];
CLLocationCoordinate2D location;
    location.latitude = (double) 23.00000;
    location.longitude = (double) 73.00000;


CLLocationCoordinate2D location2;
    location2.latitude = (double) 73.00000;
    location2.longitude = (double) 23.00000;

    CLLocation *locationPoint1 = [[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longitude];
    CLLocation *locationPoint2 = [[CLLocation alloc]initWithLatitude:location2.latitude longitude:location2.longitude]; 
    [self.points addObject:locationPoint1];
    [self.points addObject:locationPoint2];
[self performSelector:@selector(drowRoute)];
}


-(void)drowRoute{
    CGContextRef context = UIGraphicsGetCurrentContext(); 
 //   CGContextSetStrokeColorWithColor(context, [[UIColor blueColor]CGColor]);
    CGContextSetLineWidth(context, 2.0);

    for(int idx = 0; idx < self.points.count; idx++)
    {
        CLLocation* location = [self.points objectAtIndex:idx];
        CGPoint point = [mapView convertCoordinate:location.coordinate toPointToView:self.view];

        if(idx == 0)
        {
            // move to the first point
            CGContextMoveToPoint(context, point.x, point.y);
        }
        else
        {
            CGContextAddLineToPoint(context, point.x, point.y);
        }
    }
    CGContextStrokePath(context);
}

4 个答案:

答案 0 :(得分:2)

我使用谷歌地图服务。您只需将经度和纬度作为参数传递给URL,Google地图就会照顾休息。

- (void)viewDidLoad
{
  [super viewDidLoad];
  locationManager = [[CLLocationManager alloc] init];
  locationManager.delegate = self;
  locationManager.distanceFilter = kCLDistanceFilterNone; 
  locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; 
  [locationManager startUpdatingLocation];

    NSString *url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f",c_lat,c_long,lat,lat];
  //saddr= we pass source address long, lat.
  //daddr= we pass destination address long, lat.

  //--------use this if you have current long,lat and destination's address or street name etc...

   NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%@",
                currentLocation.latitude, currentLocation.longitude,
                [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
   //------------------------------------------------------------------------------
   [[UIApplication sharedApplication] openURL: [NSURL URLWithString:url]]; // this line will open Google map on Maps application on device and in Safari in Simulator.


}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

  curntloc = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];

 NSLog(@"in func--> %f %f",curntloc.coordinate.latitude, curntloc.coordinate.longitude);
}

答案 1 :(得分:1)

以下是使用lat,long坐标在地图上绘制路线的示例源代码。

http://developer.apple.com/library/ios/#samplecode/Breadcrumb/Introduction/Intro.html

这就是我学会完成任务的方法。

此外,要绘制线条,在this post中您会找到注释类。查看帖子中的源代码,我希望能为您提供更多帮助。

通过使用我发布的第二个链接中的类,您只需提供坐标(lat,long),其余类将完成:)

答案 2 :(得分:1)

使用以下代码:

-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, [encoded length])];
    NSInteger len = [encoded length];
    NSInteger index = 0;
    NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
    NSInteger lat=0;
    NSInteger lng=0;
    while (index < len) {
        NSInteger b;
        NSInteger shift = 0;
        NSInteger result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        NSNumber *latitude = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];
        NSNumber *longitude = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];
        CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] autorelease];
        [array addObject:loc];
    }

    return array;
}
-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t {
    NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude];
    NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude];

    NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@", saddr, daddr];
    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];

    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl];
    NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];

    return [self decodePolyLine:[encodedPoints mutableCopy]];
}
-(void) centerMap {
    MKCoordinateRegion region;

    CLLocationDegrees maxLat = -90;
    CLLocationDegrees maxLon = -180;
    CLLocationDegrees minLat = 90;
    CLLocationDegrees minLon = 180;
    for(int idx = 0; idx < routes.count; idx++)
    {
        CLLocation* currentLocation = [routes objectAtIndex:idx];
        if(currentLocation.coordinate.latitude > maxLat)
            maxLat = currentLocation.coordinate.latitude;
        if(currentLocation.coordinate.latitude < minLat)
            minLat = currentLocation.coordinate.latitude;
        if(currentLocation.coordinate.longitude > maxLon)
            maxLon = currentLocation.coordinate.longitude;
        if(currentLocation.coordinate.longitude < minLon)
            minLon = currentLocation.coordinate.longitude;
    }
    region.center.latitude     = (maxLat + minLat) / 2;
    region.center.longitude    = (maxLon + minLon) / 2;
    region.span.latitudeDelta  = maxLat - minLat;
    region.span.longitudeDelta = maxLon - minLon;

    [mapView setRegion:region animated:YES];
}
-(void) calculate_distance{
    float target = [location1 distanceFromLocation:location2]/1000;
    text2=[NSString stringWithFormat:@"%fkm",target];
    routes = [[self calculateRoutesFrom:location1.coordinate to:location2.coordinate] retain];

    if([routes count]!=0){
        [self updateRouteView];
        [self centerMap];
        UIAlertView* alert1=[[UIAlertView alloc]initWithTitle:@"MESSAGE" message:text2 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
    }
    else{
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"MESSAGE" message:@"We could not draw direction between your desired locations" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

    location1=0;
    location2=0;
}
-(void) updateRouteView {
    CGContextRef context =  CGBitmapContextCreate(nil, 
                                                  routeView.frame.size.width, 
                                                  routeView.frame.size.height, 
                                                  8, 
                                                  4 * routeView.frame.size.width,
                                                  CGColorSpaceCreateDeviceRGB(),
                                                  kCGImageAlphaPremultipliedLast);

    CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
    CGContextSetLineWidth(context, 3.0);

    for(int i = 0; i < routes.count; i++) {
        CLLocation* location = [routes objectAtIndex:i];
        CGPoint point = [mapView convertCoordinate:location.coordinate toPointToView:routeView];

        if(i == 0) {
            CGContextMoveToPoint(context, point.x, routeView.frame.size.height - point.y);
        } else {
            CGContextAddLineToPoint(context, point.x, routeView.frame.size.height - point.y);
        }
    }

    CGContextStrokePath(context);

    CGImageRef image = CGBitmapContextCreateImage(context);
    UIImage* img = [UIImage imageWithCGImage:image];

    routeView.image = img;
    CGContextRelease(context);

}

答案 3 :(得分:0)

我使用下面给出的代码在两个位置之间绘制路线:

GitHub