在多个位置之间绘制地图路径

Posted

技术标签:

【中文标题】在多个位置之间绘制地图路径【英文标题】:Draw Map Path among multiple location 【发布时间】:2013-07-08 06:37:06 【问题描述】:

我是 iphone 开发新手,我想在 5 个位置之间绘制路径,如何在谷歌地图中绘制路径。 我想要从 location1 到 location2 、 location2 到 location3 、 location3 到 location4 和 location4 到 location5 的路径。

这是我的代码

- (void)viewDidLoad 
[super viewDidLoad];

NSDictionary *d1,*d2,*d3,*d4,*d5;

d1=[NSDictionary dictionaryWithObjectsAndKeys:@"location1",@"comments",@"1",@"id",@"23.02941395",@"latitude",@"72.54620655",@"longitude",nil];
d2=[NSDictionary dictionaryWithObjectsAndKeys:@"location2",@"comments",@"2",@"id",@"23.028359049999995",@"latitude",@"72.54537318333334",@"longitude",nil];
d3=[NSDictionary dictionaryWithObjectsAndKeys:@"location3",@"comments",@"3",@"id",@"23.029545",@"latitude",@"72.546036",@"longitude",nil];
d4=[NSDictionary dictionaryWithObjectsAndKeys:@"location4",@"comments",@"4",@"id",@"23.030050",@"latitude",@"72.546226",@"longitude",nil];
d5=[NSDictionary dictionaryWithObjectsAndKeys:@"location5",@"comments",@"5",@"id",@"23.030050",@"latitude",@"72.546022",@"longitude",nil];


self.reports=[NSArray arrayWithObjects:d1,d2,d3,d4,d5,nil];


for (NSDictionary *d in self.reports) 
    float latitude=[[d valueForKey:@"latitude"] floatValue];
    float longitude=[[d valueForKey:@"longitude"] floatValue];

    Place* home = [[[Place alloc] init] autorelease];
    home.name = [d valueForKey:@"comments"];
    home.latitude = latitude;
    home.longitude = longitude;

    PlaceMark *from = [[[PlaceMark alloc] initWithPlace:home] autorelease];             
    [mapView addAnnotation:from];




[self centerMap];

   

   -(void) centerMap 

   
MKCoordinateRegion region;
CLLocationDegrees maxLat = -90;
CLLocationDegrees maxLon = -180;
CLLocationDegrees minLat = 120;
CLLocationDegrees minLon = 150;
NSMutableArray *temp=[NSArray arrayWithArray:self.reports];
NSLog(@"%@",temp);
for (int i=0; i<[temp count];i++) 
    Place* home = [[[Place alloc] init] autorelease];
    home.latitude = [[[temp objectAtIndex:i] valueForKey:@"latitude"]floatValue];
    home.longitude =[[[temp objectAtIndex:i] valueForKey:@"longitude"]floatValue];

    PlaceMark* from = [[[PlaceMark alloc] initWithPlace:home] autorelease];     

    CLLocation* currentLocation = (CLLocation*)from ;
    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];

    
     - (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id  <MKAnnotation>)annotation
   

if (annotation == mapView.userLocation) 
    return nil;

MKPinAnnotationView *pin = (MKPinAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier: @"asdf"];

if (pin == nil)
    pin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier: @"asdf"] autorelease];
else
    pin.annotation = annotation;
pin.userInteractionEnabled = YES;
UIButton *disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 
[disclosureButton setFrame:CGRectMake(0, 0, 30, 30)];

pin.rightCalloutAccessoryView = disclosureButton;
pin.pinColor = MKPinAnnotationColorRed;
//pin.animatesDrop = YES;
[pin setEnabled:YES];
[pin setCanShowCallout:YES];
return pin;

   

    - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view  calloutAccessoryControlTapped:(UIControl *)control
    
NSString *strTitle = [NSString stringWithFormat:@"%@",[view.annotation title]];
NSMutableDictionary *d;
NSMutableArray *temp=[NSArray arrayWithArray:self.reports];


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

    d = (NSMutableDictionary*)[temp objectAtIndex:i];
    NSString *strAddress = [NSString stringWithFormat:@"%@",[d valueForKey:@"comments"]];

    if([strAddress isEqualToString:strTitle]) 
        [self presentModalViewController:self.nxtDetailsVCtr animated:YES];
        [self.nxtDetailsVCtr.lblDetail setText:strAddress];     
        break;
    



    

【问题讨论】:

作为参考,我有这段代码,但我想在其中绘制路径。 sugartin-info.googlecode.com/files/MapkitDemo.zip 【参考方案1】:

您可以使用NVPlolineAnnotation 在地图内画线。这是Source Code。

【讨论】:

【参考方案2】:

需要框架

QuartzCore.framework CoreLocation.framework MapKit.framework

需要的文件

JSONKit.h JSONKit.m

在 ARC 的情况下,在 JSON 的编译源中设置 -fno-objc-arc。

在头文件中

__block IBOutlet MKMapView *__mapView;
NSArray* routes;

MKPointAnnotation *startLocation;
MKPointAnnotation *endLocation;

MKPolyline *polyLine;

实现一段代码...

- (void)viewDidLoad

//    [__mapView setShowsUserLocation:YES];
    [__mapView setZoomEnabled:YES];
    [__mapView setScrollEnabled:YES];
    [__mapView setMapType:MKMapTypeStandard];
    [__mapView setDelegate:self];

    routes=[[NSArray alloc] init];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


- (IBAction)drawPath:(id)sender 

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
        //Background Thread
        [self showRouteFrom:startLocation to:endLocation];
        dispatch_async(dispatch_get_main_queue(), ^(void)
            //Run UI Updates

            if (polyLine) 
                [__mapView setVisibleMapRect:[polyLine boundingMapRect]];
                [__mapView addOverlay:polyLine];

                [self centerMap];
            

            NSLog(@"drawing path completed");
        );
    );



-(void) showRouteFrom: (id<MKAnnotation>)source to:(id<MKAnnotation>)destination;

    if(routes)
    
        [__mapView removeAnnotations:[__mapView annotations]];
    

    [__mapView addAnnotation:source];
    [__mapView addAnnotation:destination];

    NSLog(@"source title is %@",source.title);
    NSLog(@"destination title is %@",destination.title);

    routes = [self calculateRoutesFrom:source.coordinate to:destination.coordinate];
    NSLog(@"routes are %@",routes);

    NSInteger numberOfSteps = routes.count;

    CLLocationCoordinate2D coordinates[numberOfSteps];
    for (NSInteger index = 0; index < numberOfSteps; index++)
    
        CLLocation *location = [routes objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;
        coordinates[index] = coordinate;
    

    polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];

    NSLog(@"poly line to be added as ovelay is %@",polyLine);


-(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.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false&avoid=highways&mode=",saddr,daddr];

    NSLog(@"Fired API %@",apiUrlStr);

    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];

    NSError* error = nil;
    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];

    NSDictionary *dic=[apiResponse objectFromJSONString];

    if (dic!=nil) 
        NSArray *routPoints=[[NSArray alloc] initWithArray:[dic valueForKey:@"routes"]];

        NSDictionary *polylineOverview=[[routPoints objectAtIndex:0] valueForKey:@"overview_polyline"];
        NSString *polylinePoints = [polylineOverview objectForKey:@"points"];
        return [self decodePolyLine:[polylinePoints mutableCopy]];
    

    return nil;



- (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];
    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];
        NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
        //printf("[%f,", [latitude doubleValue]);
        //printf("%f]", [longitude doubleValue]);
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
        [array addObject:loc];
    
    return array;


#pragma mark- MKMapView delegate method

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay

    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor purpleColor];
    polylineView.lineWidth = 5.0;

    NSLog(@"polyline in viewFor overlay: %@",polylineView);
    return polylineView;


- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation

    NSLog(@"did update user location called ");
    MKCoordinateRegion region;

    region.span.latitudeDelta = .005;
    region.span.longitudeDelta = .005;
    region.center = userLocation.coordinate;

    [mapView setRegion:region animated:YES];


-(void) centerMap

    MKCoordinateRegion region;
    CLLocationDegrees maxLat = -90.0;
    CLLocationDegrees maxLon = -180.0;
    CLLocationDegrees minLat = 90.0;
    CLLocationDegrees minLon = 180.0;

    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.0;
    region.center.longitude    = (maxLon + minLon) / 2.0;
    region.span.latitudeDelta = 0.01;
    region.span.longitudeDelta = 0.01;

    region.span.latitudeDelta  = ((maxLat - minLat)<0.0)?100.0:(maxLat - minLat);
    region.span.longitudeDelta = ((maxLon - minLon)<0.0)?100.0:(maxLon - minLon);
    [__mapView setRegion:region animated:YES];


#pragma mark-  UITextField delegate method

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

    [self.view bringSubviewToFront:textField];

    CGRect rect=textField.frame;

    [[NSUserDefaults standardUserDefaults] setValue:NSStringFromCGRect(rect) forKey:@"textFieldRect"];

    rect.origin.y=self.view.frame.size.height-260;

    [UIView animateWithDuration:0.3 animations:^
        [textField setFrame:rect];
    ];

    return YES;



- (BOOL)textFieldShouldReturn:(UITextField *)textField

    NSString *rectStr=[[NSUserDefaults standardUserDefaults] valueForKey:@"textFieldRect"];
    NSArray *rectArray=[rectStr componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]];

    CGRect rect;

    rect.origin.x=[[rectArray objectAtIndex:2] floatValue];
    rect.origin.y=[[rectArray objectAtIndex:4] floatValue];
    rect.size.width=[[rectArray objectAtIndex:8] floatValue];
    rect.size.height=[[rectArray objectAtIndex:10] floatValue];

    [UIView animateWithDuration:0.3 animations:^
        [textField setFrame:rect];
    ];
    [textField resignFirstResponder];
    return YES;



- (void)textFieldDidEndEditing:(UITextField *)textField

    NSDictionary *locationDic=[self getLatLongOfPlace:[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
    NSDictionary *latLongDic=[[[[[locationDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"]valueForKey:@"viewport"] valueForKey:@"northeast"];

    if (textField.tag==0) 
        startLocation=[[MKPointAnnotation alloc] init];
        [startLocation setCoordinate:CLLocationCoordinate2DMake([[latLongDic valueForKey:@"lat"] floatValue], [[latLongDic valueForKey:@"lng"] floatValue])];
        startLocation.title=[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    else
        endLocation=[[MKPointAnnotation alloc] init];
        [endLocation setCoordinate:CLLocationCoordinate2DMake([[latLongDic valueForKey:@"lat"] floatValue], [[latLongDic valueForKey:@"lng"] floatValue])];
        endLocation.title=[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    

    NSLog(@"object at index is viewport %@",[[[[[locationDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"]valueForKey:@"viewport"] valueForKey:@"northeast"]);


#pragma mark Getting lat long from place name.

-(NSDictionary*)getLatLongOfPlace:(NSString*)place

    NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=true",place];

    NSLog(@"Fired URL:- %@",apiUrlStr);

    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];

    NSError* error = nil;
    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];

    NSDictionary *dic=[apiResponse objectFromJSONString];
    return dic;

这里是SampleCode我做的

注意:--- 如果示例对您不起作用,请在 viewDidLoad 方法中输入这一行

// [__mapView setShowsUserLocation:YES];

截图

【讨论】:

我不想在两个位置之间绘制路径,我想在多个位置之间绘制路径...如果您有任何示例代码,请给我。 如果你有 5 个位置,然后使用从 1 到 2、2 到 3、3 到 4 和 3 到 5 的路径进行绘制。就是这样。只需调用 showRouteFrom 即可通过发送位置进行绘制。源 lat long 和目标 lat long 作为参数【参考方案3】:
          #import "ViewController.h"
          #import "JSONKit.h"

         @interface ViewController ()

    @end

    @implementation ViewController

    NSMutableArray *locationarry ;
    NSMutableDictionary * citywiselatlong ;


    - (void)viewDidLoad
    

      locationarry = [[NSMutableArray alloc]initWithObjects:@"Ahmedabad",@"Rajkot",@"Baroda",@"Surat", nil];

citywiselatlong = [[NSMutableDictionary alloc]init];



[self locationfind];

NSMutableString* TotalXMLString = [[NSMutableString alloc]init];

[TotalXMLString appendFormat:@"http://maps.googleapis.com/maps/api/distancematrix/json?origins="];

[TotalXMLString appendFormat:@"%@,%@&destinations=",[[citywiselatlong valueForKey:[locationarry objectAtIndex:0]] valueForKey:@"lat"] ,[[citywiselatlong valueForKey:[locationarry objectAtIndex:0]] valueForKey:@"lng"]];


for (int i = 1; i < [locationarry count]; i++) 

    [TotalXMLString appendFormat:@"%@,%@",[[citywiselatlong valueForKey:[locationarry objectAtIndex:i]] valueForKey:@"lat"] ,[[citywiselatlong valueForKey:[locationarry objectAtIndex:i]] valueForKey:@"lng"]];

    if (i != [locationarry count] -1 ) 
        [TotalXMLString appendFormat:@"|"];
    
    else
    
        [TotalXMLString appendFormat:@"&mode=driving&sensor=false"];
    




NSURL* apiUrl = [NSURL URLWithString:[TotalXMLString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];

NSDictionary *dic=[apiResponse objectFromJSONString];
NSLog(@"%@",dic);


NSMutableArray * distance = [[NSMutableArray alloc]initWithArray:[[[[dic valueForKey:@"rows"] objectAtIndex:0] valueForKey:@"elements"]valueForKey:@"distance"]];



for (int j= 0 ; j < [distance count]; j++) 

    NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithDictionary:[distance objectAtIndex:j]];




 NSLog(@"%@",distance);

[__mapView setShowsUserLocation:YES];
[__mapView setZoomEnabled:YES];
[__mapView setScrollEnabled:YES];
[__mapView setMapType:MKMapTypeHybrid];
[__mapView setDelegate:self];



routes=[[NSArray alloc] init];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.


 

 - (void)didReceiveMemoryWarning
 
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 


   #pragma mark- MKMapView delegate method

  - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
 
MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
polylineView.strokeColor = [UIColor purpleColor];
polylineView.lineWidth = 5.0;

NSLog(@"polyline in viewFor overlay: %@",polylineView);
return polylineView;
  

  - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
   
NSLog(@"did update user location called ");
MKCoordinateRegion region;

region.span.latitudeDelta = .005;
region.span.longitudeDelta = .005;
region.center = userLocation.coordinate;

[mapView setRegion:region animated:YES];
   


   - (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];
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];
    NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
    //printf("[%f,", [latitude doubleValue]);
    //printf("%f]", [longitude doubleValue]);
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
    [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.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false&avoid=highways&mode=",saddr,daddr];

NSLog(@"Fired API %@",apiUrlStr);

NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];

NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];

NSDictionary *dic=[apiResponse objectFromJSONString];

if (dic!=nil) 
    NSArray *routPoints=[[NSArray alloc] initWithArray:[dic valueForKey:@"routes"]];

    NSDictionary *polylineOverview=[[routPoints objectAtIndex:0] valueForKey:@"overview_polyline"];
    NSString *polylinePoints = [polylineOverview objectForKey:@"points"];
    return [self decodePolyLine:[polylinePoints mutableCopy]];


return nil;
    


  - (IBAction)drawPath:(id)sender 

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
    //Background Thread
    [self showRouteFrom:startLocation to:endLocation];
    dispatch_async(dispatch_get_main_queue(), ^(void)
        //Run UI Updates

        if (polyLine) 
            [__mapView setVisibleMapRect:[polyLine boundingMapRect]];
            [__mapView addOverlay:polyLine];
        

        NSLog(@"drawing path completed");
    );
);
    

  -(void) showRouteFrom: (id<MKAnnotation>)source to:(id<MKAnnotation>)destination;
   
  routes = [self calculateRoutesFrom:source.coordinate to:destination.coordinate];
NSLog(@"routes are %@",routes);

NSInteger numberOfSteps = routes.count;

CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++)

    CLLocation *location = [routes objectAtIndex:index];
    CLLocationCoordinate2D coordinate = location.coordinate;
    coordinates[index] = coordinate;


polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];


[polyLineArray addObject:polyLine];

    

   - (IBAction)drawMultiple:(id)sender
   
polyLineArray=[[NSMutableArray alloc] init];


MKPointAnnotation *start=[[MKPointAnnotation alloc] init];
MKPointAnnotation *end=[[MKPointAnnotation alloc] init];

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
    //Background Thread

    for (int i=0;i<locationarry.count-1;i++)
    
         NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];

        NSDictionary *dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];

        [start setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];

       part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i +1 ] componentsSeparatedByString:@","]];
       dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];

        [end setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];

        [self showRouteFrom:start to:end];

    
    dispatch_async(dispatch_get_main_queue(), ^(void)
        //Run UI Updates


         NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:0] componentsSeparatedByString:@","]];

        NSDictionary *tempDic=[[NSDictionary alloc] initWithDictionary:[citywiselatlong objectForKey:[part objectAtIndex:0]]];

        [start setCoordinate:CLLocationCoordinate2DMake([[tempDic valueForKey:@"lat"] floatValue], [[tempDic valueForKey:@"lng"] floatValue])];

        if (polyLine) 
            [__mapView setVisibleMapRect:[polyLine boundingMapRect]];
            for (MKPolyline *pLine in polyLineArray) 
                [__mapView addOverlay:pLine];
            
        


        for (int i =0 ; i< [locationarry count]; i ++)
        
             NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];

            NSDictionary *dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];

            MKPointAnnotation *first=[[MKPointAnnotation alloc] init];
            MKPointAnnotation *second=[[MKPointAnnotation alloc] init];

            [first setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];

            if(i+1<[locationarry count])
            
               NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i + 1] componentsSeparatedByString:@","]];

                dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];

                [second setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];
            
            else
            
                NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];
                dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];;

                [second setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];

            

            if (i==0)
            
                [__mapView addAnnotation:first];
                [__mapView addAnnotation:second];
            
            else
            
                [__mapView addAnnotation:second];

            
        


        NSLog(@"drawing path completed");
    );
   );
      

   -(void) centerMap
  
MKCoordinateRegion region;
CLLocationDegrees maxLat = -90.0;
CLLocationDegrees maxLon = -180.0;
CLLocationDegrees minLat = 90.0;
CLLocationDegrees minLon = 180.0;

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.0;
region.center.longitude    = (maxLon + minLon) / 2.0;
region.span.latitudeDelta = 0.01;
region.span.longitudeDelta = 0.01;

region.span.latitudeDelta  = ((maxLat - minLat)<0.0)?100.0:(maxLat - minLat);
region.span.longitudeDelta = ((maxLon - minLon)<0.0)?100.0:(maxLon - minLon);
[__mapView setRegion:region animated:YES];
     


  #pragma mark-  UITextField delegate method


   -(void)locationfind
   

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

    NSDictionary *locationDic=[self getLatLongOfPlace:[[locationarry objectAtIndex:i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
    NSDictionary *latLongDic=[[[[locationDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"]valueForKey:@"location"];

    NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];

     [citywiselatlong setObject:latLongDic forKey:[part objectAtIndex:0]];
    NSLog(@"%@",citywiselatlong);



    

   #pragma mark Getting lat long from place name.

   -(NSDictionary*)getLatLongOfPlace:(NSString*)place
  
NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=true",place];

NSLog(@"Fired URL:- %@",apiUrlStr);

NSURL* apiUrl = [NSURL URLWithString:[apiUrlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];

NSDictionary *dic=[apiResponse objectFromJSONString];
return dic;
    

 @end

【讨论】:

【参考方案4】:

对于绘制多个点,您可以将其用作

需要在头文件中声明可变数组

NSMutableArray *polyLineArray; 

实现文件需要小改动,因为 ===

-(void) showRouteFrom: (id<MKAnnotation>)source to:(id<MKAnnotation>)destination;

    NSLog(@"source title is %@",source.title);
    NSLog(@"destination title is %@",destination.title);

    routes = [self calculateRoutesFrom:source.coordinate to:destination.coordinate];
    NSLog(@"routes are %@",routes);

    NSInteger numberOfSteps = routes.count;

    CLLocationCoordinate2D coordinates[numberOfSteps];
    for (NSInteger index = 0; index < numberOfSteps; index++)
    
        CLLocation *location = [routes objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;
        coordinates[index] = coordinate;
    

    polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
    [polyLineArray addObject:polyLine];

//    NSLog(@"poly line to be added as ovelay is %@",polyLine);



- (IBAction)drawMultiple:(id)sender
    
    polyLineArray=[[NSMutableArray alloc] init];

   NSDictionary *kolkata,*delhi,*chennai,*mumbai,*pune;

   kolkata=[NSDictionary dictionaryWithObjectsAndKeys:@"location1",@"comments",@"1",@"id",@"23.0083321",@"latitude",@"88.54276659999",@"longitude",nil];
    delhi=[NSDictionary dictionaryWithObjectsAndKeys:@"location2",@"comments",@"2",@"id",@"28.889816",@"latitude",@"77.3418147",@"longitude",nil];
    chennai=[NSDictionary dictionaryWithObjectsAndKeys:@"location3",@"comments",@"3",@"id",@"13.23339843",@"latitude",@"80.3322912",@"longitude",nil];
    mumbai=[NSDictionary dictionaryWithObjectsAndKeys:@"location4",@"comments",@"4",@"id",@"19.2716339",@"latitude",@"72.9864994",@"longitude",nil];
    pune=[NSDictionary dictionaryWithObjectsAndKeys:@"location5",@"comments",@"5",@"id",@"18.6346965",@"latitude",@"73.9894867",@"longitude",nil];

    NSArray *arrayOfLocations=[[NSArray alloc] initWithObjects:kolkata,delhi,chennai,mumbai,pune,nil];

    MKPointAnnotation *start=[[MKPointAnnotation alloc] init];
    MKPointAnnotation *end=[[MKPointAnnotation alloc] init];

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
        //Background Thread

        for (int i=0;i<arrayOfLocations.count-1;i++)
        
            NSDictionary *dic=[arrayOfLocations objectAtIndex:i];

            [start setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"latitude"] floatValue], [[dic valueForKey:@"longitude"] floatValue])];

            dic=[arrayOfLocations objectAtIndex:i+1];

            [end setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"latitude"] floatValue], [[dic valueForKey:@"longitude"] floatValue])];

            [self showRouteFrom:start to:end];
        

        dispatch_async(dispatch_get_main_queue(), ^(void)
            //Run UI Updates

            NSDictionary *tempDic=[[NSDictionary alloc] initWithDictionary:[arrayOfLocations objectAtIndex:0]];

            [start setCoordinate:CLLocationCoordinate2DMake([[tempDic valueForKey:@"latitude"] floatValue], [[tempDic valueForKey:@"longitude"] floatValue])];


            [__mapView addAnnotation:start];
            [__mapView addAnnotation:end];

            if (polyLine) 
                [__mapView setVisibleMapRect:[polyLine boundingMapRect]];
                for (MKPolyline *pLine in polyLineArray) 
                    [__mapView addOverlay:pLine];
                
            

            NSLog(@"drawing path completed");
        );
    );

If u need sample code here it is

输出是--------

【讨论】:

谢谢这正是我想要的......现在我想在所有位置上放置注释。【参考方案5】:

这里使用BreadCrumbs是示例代码..非常有用...您可以根据您的要求自定义代码

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

【讨论】:

以上是关于在多个位置之间绘制地图路径的主要内容,如果未能解决你的问题,请参考以下文章

使用 GPS Provider 在地图上使用设备的当前位置绘制路线

如何在苹果地图中的两个位置之间绘制路线。通过 openURL

在 Android 中步行/驾驶时更新位置标记并在 Google 地图上绘制路径

如何保存谷歌地图绘制的折线路径?

如何使用javascript在谷歌地图中的多个标记之间绘制路线图

在谷歌地图静态api中绘制圆形路径