iPhone:如何在MapKit上的两点之间画线?

Azh*_*har 14 iphone objective-c mapkit ipad ios

我有两点的纬度和经度,并希望在MapKit上使用Pin在这两点之间画线.

我用谷歌搜索但找不到合适的解决方案,因为我找到的是用数据点数组绘制叠加层,但我在这两点之间没有任何点数.

只需两点,并希望在这两点之间画线.

请帮忙.

gra*_*ver 48

首先让您的视图控制器实现MKMapViewDelegate协议并声明您需要的属性:

@property (nonatomic, retain) MKMapView *mapView; //this is your map view
@property (nonatomic, retain) MKPolyline *routeLine; //your line
@property (nonatomic, retain) MKPolylineView *routeLineView; //overlay view
Run Code Online (Sandbox Code Playgroud)

然后在viewDidLoad(例如,或初始化的任何地方)

//initialize your map view and add it to your view hierarchy - **set its delegate to self***
CLLocationCoordinate2D coordinateArray[2];
coordinateArray[0] = CLLocationCoordinate2DMake(lat1, lon1); 
coordinateArray[1] = CLLocationCoordinate2DMake(lat2, lon2);


self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
[self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible

[self.mapView addOverlay:self.routeLine];
Run Code Online (Sandbox Code Playgroud)

然后实现MKMapViewDelegate的方法-(MKOverlayView *)mapView:viewForOverlay:

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if(overlay == self.routeLine)
    {
        if(nil == self.routeLineView)
        {
            self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
            self.routeLineView.fillColor = [UIColor redColor];
            self.routeLineView.strokeColor = [UIColor redColor];
            self.routeLineView.lineWidth = 5;

        }

        return self.routeLineView;
    }

    return nil;
}
Run Code Online (Sandbox Code Playgroud)

您可以调整代码以满足您的需要,但是对于2个或更多点来说,它非常简单.


Abh*_*ngh 8

请参阅本教程以在mkmapview中绘制折线或路线

1> 使用mapkit绘制路线

2>从ios4.0以上版本您可以使用MKOverlayPathView参见Apple Docs

示例代码: -

创建PolyLine: -

    -(void) loadRoute
    {
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@”route” ofType:@”csv”];
    NSString* fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSArray* pointStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    MKMapPoint northEastPoint;
    MKMapPoint southWestPoint; 

   MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * pointStrings.count);

    for(int idx = 0; idx < pointStrings.count; idx++)
    {
    NSString* currentPointString = [pointStrings objectAtIndex:idx];
    NSArray* latLonArr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];

    CLLocationDegrees latitude = [[latLonArr objectAtIndex:0] doubleValue];
    CLLocationDegrees longitude = [[latLonArr objectAtIndex:1] doubleValue];

    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);

    MKMapPoint point = MKMapPointForCoordinate(coordinate);

        if (idx == 0) {
    northEastPoint = point;
    southWestPoint = point;
    }
    else
    {
    if (point.x > northEastPoint.x)
    northEastPoint.x = point.x;
    if(point.y > northEastPoint.y)
    northEastPoint.y = point.y;
    if (point.x < southWestPoint.x)
    southWestPoint.x = point.x;
    if (point.y < southWestPoint.y)
    southWestPoint.y = point.y;
    }

    pointArr[idx] = point;

    }

        self.routeLine = [MKPolyline polylineWithPoints:pointArr count:pointStrings.count];

    _routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y);

        free(pointArr);

    } 
Run Code Online (Sandbox Code Playgroud)

显示PoluLine: -

[self.mapView addOverlay:self.routeLine]; 
Run Code Online (Sandbox Code Playgroud)

单独添加叠加层不会在地图上渲染任何内容.您的MKMapViewDelegate实现必须返回您刚添加的此路由的叠加层,因为简单地添加将无济于事.

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay
{
MKOverlayView* overlayView = nil;

if(overlay == self.routeLine)
{
//if we have not yet created an overlay view for this overlay, create it now.
if(nil == self.routeLineView)
{
self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
self.routeLineView.fillColor = [UIColor redColor];
self.routeLineView.strokeColor = [UIColor redColor];
self.routeLineView.lineWidth = 3;
}

overlayView = self.routeLineView;

}

return overlayView;

} 
Run Code Online (Sandbox Code Playgroud)


Gam*_*esh 8

在此输入图像描述

#import <MapKit/MapKit.h>   

- (void)viewDidLoad
{
        [mapview setDelegate:self];
        mapview.showsUserLocation = YES; 
}

- (CLLocationCoordinate2D)coordinateWithLocation:(NSDictionary*)location
{
    double latitude = [[location objectForKey:@"lat"] doubleValue];
    double longitude = [[location objectForKey:@"lng"] doubleValue];

    return CLLocationCoordinate2DMake(latitude, longitude);
}

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

    MKCoordinateSpan span = MKCoordinateSpanMake(0.005, 0.005);
    MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);

    [mapview setRegion:region];

    [mapview setCenterCoordinate:userLocation.coordinate animated:YES];
    NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%@&sensor=true", mapview.userLocation.location.coordinate.latitude,  mapview.userLocation.location.coordinate.longitude, @"24.1620661,72.394131"];


    //http://maps.googleapis.com/maps/api/directions/json?origin=23.030000,72.580000&destination=23.400000,72.750000&sensor=true

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

    NSLog(@"%@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    NSError *error = nil;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

    NSArray *routes = [result objectForKey:@"routes"];
        NSLog(@"%@",routes);

    NSDictionary *firstRoute = [routes objectAtIndex:0];

    NSDictionary *leg =  [[firstRoute objectForKey:@"legs"] objectAtIndex:0];

    NSDictionary *end_location = [leg objectForKey:@"end_location"];

       NSLog(@"dDDDDDD>>>>>>%@",leg);
    double latitude = [[end_location objectForKey:@"lat"] doubleValue];
    double longitude = [[end_location objectForKey:@"lng"] doubleValue];

    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);

    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    point.coordinate = coordinate;
    point.title =  [leg objectForKey:@"end_address"];
    point.subtitle = @"I'm here!!!";

    [self.mapview addAnnotation:point];

    NSArray *steps = [leg objectForKey:@"steps"];

    int stepIndex = 0;

    CLLocationCoordinate2D stepCoordinates[1  + [steps count] + 1];

    stepCoordinates[stepIndex] = userLocation.coordinate;

    for (NSDictionary *step in steps) {

        NSDictionary *start_location = [step objectForKey:@"start_location"];
        stepCoordinates[++stepIndex] = [self coordinateWithLocation:start_location];

        if ([steps count] == stepIndex){
            NSDictionary *end_location = [step objectForKey:@"end_location"];
            stepCoordinates[++stepIndex] = [self coordinateWithLocation:end_location];
        }
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:stepCoordinates count:1 + stepIndex];
    [mapview addOverlay:polyLine];

    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake((userLocation.location.coordinate.latitude + coordinate.latitude)/2, (userLocation.location.coordinate.longitude + coordinate.longitude)/2);

}];
}
Run Code Online (Sandbox Code Playgroud)

然后实现MKMapViewDelegate的方法 - (MKOverlayView*)mapView:viewForOverlay:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor colorWithRed:204/255. green:45/255. blue:70/255. alpha:1.0];
    polylineView.lineWidth = 1;

    return polylineView;
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    static NSString *annotaionIdentifier=@"annotationIdentifier";
    MKPinAnnotationView *aView=(MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:annotaionIdentifier ];
    if (aView==nil) {

        aView=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:annotaionIdentifier];
        aView.pinColor = MKPinAnnotationColorRed;
        aView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        //        aView.image=[UIImage imageNamed:@"arrow"];
        aView.animatesDrop=TRUE;
        aView.canShowCallout = YES;
        aView.calloutOffset = CGPointMake(-5, 5);
    }

    return aView;
}
Run Code Online (Sandbox Code Playgroud)


Kau*_*iya 5

在mapview中设置Pin和绘制线.

First of all Add frame work
    1 Foundation.framework
    2 CoreGraphics.framework
    3 CoreLocation.framework
    4 MapKit.framework
Run Code Online (Sandbox Code Playgroud)

然后创建nsobject文件,请参阅.... TrailsMap.h文件

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface TrailsMap : NSObject<MKAnnotation>
{
    CLLocationCoordinate2D coordinate;

    NSString *title;
    NSString *image;
    NSString *subtitle;
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic,copy) NSString *title;
@property (nonatomic,copy) NSString *image;
@property (nonatomic,copy) NSString *subtitle;

- (id)initWithLocation:(CLLocationCoordinate2D)coord;
Run Code Online (Sandbox Code Playgroud)

TrailsMap.m

#import "TrailsMap.h"

@implementation TrailsMap
@synthesize coordinate,title,image,subtitle;

- (id)initWithLocation:(CLLocationCoordinate2D)coord{

    self = [super init];
    if (self) {
        coordinate = coord;

    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

现在在mainview中创建编码请参阅..

ViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>


@interface ViewController : UIViewController<MKMapViewDelegate>

@property (strong, nonatomic) IBOutlet MKMapView *MapView;
@property (nonatomic, retain) MKPolyline *routeLine;
@property (nonatomic, retain) MKPolylineView *routeLineView;

-(void)LoadMapRoute;
@end
Run Code Online (Sandbox Code Playgroud)

最后在mainview.m文件中创建编码

ViewController.m

#import "ViewController.h"
#import "TrailsMap.h"

@interface ViewController ()
{
    NSData *alldata;
    NSMutableDictionary *data1;

   NSMutableArray *RouteLocation;
   NSMutableArray *RouteName;
}
@end

@implementation ViewController
@synthesize MapView,routeLine,routeLineView;


- (void)viewDidLoad
{
   [super viewDidLoad];

   RouteName = [[NSMutableArray alloc] initWithObjects:@"Ahmedabad",@"Rajkot", nil];
   RouteLocation = [[NSMutableArray alloc] initWithObjects:@"23.0300,72.5800",@"22.3000,70.7833", nil];
   [self LoadMapRoute];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


//-------------------------------------
// ************* Map ******************
//-------------------------------------

-(void)LoadMapRoute
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.8, 0.8);
    MKCoordinateRegion region;
    region.span = span;
    region.center= CLLocationCoordinate2DMake(23.0300,72.5800);


    // Distance between two address
   NSArray *coor1=[[RouteLocation objectAtIndex:0] componentsSeparatedByString:@","];
   CLLocation *locA = [[CLLocation alloc] initWithLatitude:[[coor1 objectAtIndex:0] doubleValue] longitude:[[coor1 objectAtIndex:1] doubleValue]];

   NSArray *coor2=[[RouteLocation objectAtIndex:1] componentsSeparatedByString:@","];
   CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[coor2 objectAtIndex:0] doubleValue] longitude:[[coor2 objectAtIndex:1] doubleValue]];
    CLLocationDistance distance = [locA distanceFromLocation:locB];
    NSLog(@"Distance :%.0f Meters",distance);


   NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", [RouteLocation objectAtIndex:0],[RouteLocation objectAtIndex:1] ];

   NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   alldata = [[NSData alloc] initWithContentsOfURL:url];

    NSError *err;
    data1 =[NSJSONSerialization JSONObjectWithData:alldata options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&err];

    if (err)
    {
        NSLog(@" %@",[err localizedDescription]);
    }

    NSArray *routes = [data1 objectForKey:@"routes"];
    NSDictionary *firstRoute = [routes objectAtIndex:0];
    NSDictionary *leg =  [[firstRoute objectForKey:@"legs"] objectAtIndex:0];
    NSArray *steps = [leg objectForKey:@"steps"];

    int stepIndex = 0;
    CLLocationCoordinate2D stepCoordinates[[steps count]+1 ];

    for (NSDictionary *step in steps)
    {

        NSDictionary *start_location = [step objectForKey:@"start_location"];
        double latitude = [[start_location objectForKey:@"lat"] doubleValue];
        double longitude = [[start_location objectForKey:@"lng"] doubleValue];
        stepCoordinates[stepIndex] = CLLocationCoordinate2DMake(latitude, longitude);

        if (stepIndex==0)
        {
            TrailsMap *point=[[TrailsMap alloc] initWithLocation:stepCoordinates[stepIndex]];
            point.title =[RouteName objectAtIndex:0];
            point.subtitle=[NSString stringWithFormat:@"Distance :%.0f Meters",distance];
            [self.MapView addAnnotation:point];
        }
        if (stepIndex==[steps count]-1)
        {
            stepIndex++;
            NSDictionary *end_location = [step objectForKey:@"end_location"];
            double latitude = [[end_location objectForKey:@"lat"] doubleValue];
            double longitude = [[end_location objectForKey:@"lng"] doubleValue];
            stepCoordinates[stepIndex] = CLLocationCoordinate2DMake(latitude, longitude);

            TrailsMap *point=[[TrailsMap alloc] initWithLocation:stepCoordinates[stepIndex]];
            point.title = [RouteName objectAtIndex:1];
            point.subtitle=[NSString stringWithFormat:@"Distance :%.0f Meters",distance];

            [self.MapView addAnnotation:point];
        }
        stepIndex++;
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:stepCoordinates count: stepIndex];
    [MapView addOverlay:polyLine];
    [MapView setRegion:region animated:YES];
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor colorWithRed:204/255. green:45/255. blue:70/255. alpha:1.0];
    polylineView.lineWidth = 5;

    return polylineView;
}
Run Code Online (Sandbox Code Playgroud)

如果您想在地图中设置多个引脚,则只需添加此代码即可.Annotaion是Objectfile.

-(void)LoadMultiplePin
{
    RouteName = [[NSMutableArray alloc] initWithObjects:@"Ahmedabad",@"Rajkot",@"Limdi", nil];
    RouteLocation = [[NSMutableArray alloc] initWithObjects:@"23.0300,72.5800",@"22.3000,70.7833",@"22.5728,71.8114", nil];

    MKCoordinateSpan span = MKCoordinateSpanMake(2.9, 2.9);
    MKCoordinateRegion region;

    region.span = span;
    region.center= CLLocationCoordinate2DMake(22.5728,71.8114);

    int cnt=RouteLocation.count;

    for (int p=0 ; p<cnt ; p++ )
    {
        NSArray *coor=[[RouteLocation objectAtIndex:p] componentsSeparatedByString:@","];

        CLLocationCoordinate2D location=CLLocationCoordinate2DMake([[coor objectAtIndex:0] doubleValue],[[coor objectAtIndex:1] doubleValue]);

        Annotaion *point=[[Annotaion alloc] initWithLocation:location];
        point.title =[RouteName objectAtIndex:p];
        [Map addAnnotation:point];
    }
    [Map setRegion:region animated:YES];

}
Run Code Online (Sandbox Code Playgroud)

通过使用此代码您可以轻松地Drope两个引脚和画线之间的两个Pin享受快乐编码... :)


Leo*_*eon 5

我从 @graver 那里得到了很好的答案,并为 Swift 3 做了这个:

// Called from viewDidLoad
func setupMap() {
    mapView.delegate = self
    // BusStop implements the MKAnnotation protocol, I have an array of them
    let routeCoordinates = busStops.map({ $0.coordinate })
    let routeLine = MKPolyline(coordinates: routeCoordinates, count: routeCoordinates.count)
    mapView.setVisibleMapRect(routeLine.boundingMapRect, animated: false)
    mapView.add(routeLine)
}

// MARK: MKMapViewDelegate

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polyline = overlay as? MKPolyline {
        let polylineRenderer = MKPolylineRenderer(overlay: polyline)
        polylineRenderer.strokeColor = .blue
        polylineRenderer.lineWidth = 3
        return polylineRenderer
    }
    return MKOverlayRenderer(overlay: overlay)
}
Run Code Online (Sandbox Code Playgroud)