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

18

我有两个点的纬度和经度,想要在MapKit上用标记绘制这两个点之间的线。

我已经搜索过了,但是没有找到适合的解决方案,因为我找到的那个方法是使用数据点数组来绘制覆盖层,但是我没有这两个点之间的任何数据点数组。

我只有两个点,想要在它们之间绘制一条线。

请帮帮我。


请查看此链接:http://spitzkoff.com/craig/?p=65 - Inder Kumar Rathore
还有这个问题 https://dev59.com/KXE85IYBdhLWcg3wUB2z - Inder Kumar Rathore
10个回答

50

首先让您的视图控制器实现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

然后在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];

然后实现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;
}
你可以调整这段代码来适应你的需求,但对于两个或更多点来说,它非常简单。

在哪个文件中实现 -(MKOverlayView *)mapView:viewForOverlay: 方法? - Saad Masood
1
@SaadMasood,在你添加了MKMapViewDelegate协议的同一个文件中。大多数情况下,这是持有MapKit视图的控制器。 - Mihail Velikov
我喜欢这个概念,但不幸的是对我来说它不起作用:无论我指定哪些坐标,我得到的都只是我的地图视图跳到东京和洛杉矶之间的某个地方。我从未看到过折线。 - Jay Versluis
1
使用MKPolylineView来显示折线覆盖层已经在iOS 7中被弃用。根据苹果文档在iOS 7及更高版本中,请使用MKPolylineRenderer类来代替MKPolylineView来显示折线覆盖层。 - invisible squirrel

8
请参考以下教程,在mkmapview中绘制折线或路线:
1>使用mapkit绘制路线 2>从ios4.0以上的版本开始,您可以使用MKOverlayPathView,请查看苹果文档 示例代码:
创建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);

    } 

显示折线:

[self.mapView addOverlay:self.routeLine]; 

仅添加覆盖层不会在地图上呈现任何内容。您的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;

} 

8

enter image description here

#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);

}];
}

然后实现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;
}

1
我正在使用Xcode 6,并使用您的代码,但是我遇到了错误coordinateWithLocation No visible interface。 - Rahul
我也遇到了同样的问题,缺少了“coordinateWithLocation”的部分。 - iOS_DEV
嗨,对我来说它运行良好,但我想去掉直线... 对我来说直线也显示出来了。 - vijay

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)
}

5

Set Pin and draw line in mapview.

First of all Add frame work
    1 Foundation.framework
    2 CoreGraphics.framework
    3 CoreLocation.framework
    4 MapKit.framework

然后创建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;

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;
}

现在在主视图中创建编码。请查看...
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

最后,在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;
}

如果您想在地图上设置多个标记,请添加以下代码。注释是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];

}

通过使用这段代码,您可以轻松地将两个引脚拖放并在这两个引脚之间绘制一条线。祝编码愉快... :)

APP 崩溃伙伴 - Anand Prakash
你能解释一下你发现的错误或崩溃的原因吗?这样我就可以帮忙了。 - Kaushik Movaliya

2

我创建了一个用Swift编写的演示程序,可以在地图上继续更新位置并绘制折线。

请按照以下步骤进行:

1)创建新项目并设置所需内容。 2)进入项目目标 -> Build Phases -> 链接二进制文件并添加 MapKit.framworkCoreLocation.framework。 3)进入Storyboard并添加地图视图,并将其与您的ViewController链接起来。 4)添加属性和委托,我提供了以下代码。

ViewController.Swift

import UIKit

import MapKit

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var mapView:MKMapView!
var locationManager: CLLocationManager!
var routeArr:[CLLocationCoordinate2D] = []
var isStarted:Bool = false

// MARK:- Life cycle
override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.delegate = self;
    locationManager.startMonitoringSignificantLocationChanges()
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.pausesLocationUpdatesAutomatically = false

    // user activated automatic authorization info mode
    let status = CLLocationManager.authorizationStatus()
    if status == .notDetermined || status == .denied || status == .authorizedWhenInUse {
           // present an alert indicating location authorization required
           // and offer to take the user to Settings for the app via
           // UIApplication -openUrl: and UIApplicationOpenSettingsURLString
           locationManager.requestAlwaysAuthorization()
           locationManager.requestWhenInUseAuthorization()
       }

    locationManager.startUpdatingLocation()
    locationManager.startUpdatingHeading()

    mapView.delegate = self
    mapView.showsUserLocation = true
    mapView.mapType = MKMapType(rawValue: 0)!
    mapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)!
}

// MARK:- Button Actions

@IBAction func startBtnClick(_ sender: Any) {
    isStarted = true
}

@IBAction func endBtnClick(_ sender: Any) {
    isStarted = false
    routeArr.removeAll()
}

// MARK:- LocationManager Delegate

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last

    if isStarted == true {
        if locations.count > 0 {
            let newLocation:CLLocationCoordinate2D = (location?.coordinate ?? nil)!
            routeArr.append(newLocation)
            DispatchQueue.main.async {
                if self.routeArr.count > 2 {
                    let route:[CLLocationCoordinate2D] = [self.routeArr[self.routeArr.count - 2] ,self.routeArr.last!]
                    print(route)
                    let polyline = MKPolyline(coordinates: route, count: route.count)
                    self.mapView.addOverlay(polyline)
                }
            }
        }
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if (overlay is MKPolyline) {
        let pr = MKPolylineRenderer(overlay: overlay)
        pr.strokeColor = UIColor.red
        pr.fillColor = .green
        pr.lineWidth = 5
        return pr
    }else {
      return MKOverlayRenderer()
    }
}

运行你的项目,点击开始按钮以跟踪,并可以在地图上看到折线。如果你点击停止按钮,则会停止绘制折线。

谢谢


1

传递你的地址协调信息

-(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];
//    NSString* apiUrlStr = @"http://maps.google.com/maps?output=dragdir&saddr=40.769264,-73.958995&daddr=47.286522,-122.312932";
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSLog(@"api url: %@", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:nil];
NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];
return [self decodePolyLine:[encodedPoints mutableCopy]];
}


-(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;
}

-(void) updateRouteView:(UIColor *)clr {
    CGContextRef context =CGBitmapContextCreate(nil,routeView.frame.size.width,routeView.frame.size.height,8,4 * routeView.frame.size.width,CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);

    CGContextSetStrokeColorWithColor(context, clr.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);

}

0

请问您能否提供任何类似的库/API名称? - Azhar
我认为GitHub和Cloud生成的链接是开源库,第一个链接最好...如果有帮助请点赞或打勾!!!!! - MCKapur
请不要只是链接到页面。你的第一个链接现在已经失效了。 - solidcell

0

在这里,您必须根据其纬度和经度计算路线,然后在MapView上绘制折线......我在我的应用程序中执行此操作....我在地图视图上绘制了所有信息的路线。

如果您使用MapKit并且还使用RagexKitLite,则这太简单了,只需获取RagexKitLite的演示即可......


0

enter image description here

获取完整代码:https://github.com/javedmultani16/MapKitWithPolyLine

绘制线条如下:

   directionsRequest.transportType = MKDirectionsTransportType.automobile

        //Draw polyline by using MKRoute so it follows the street roads...
        for (k, item) in arrayarrayPlacemarks.enumerated() {
            if k < (arrayarrayPlacemarks.count - 1) {
                directionsRequest.source = item
                directionsRequest.destination = arrayarrayPlacemarks[k+1]

                let directions = MKDirections(request: directionsRequest)
          directions.calculate { (response:MKDirections.Response!, error: Error!) -> Void in
                    if error == nil {
                        self.locRoute = response.routes[0] as? MKRoute
                        let geodesic:MKPolyline = self.locRoute!.polyline
                        self.mapView.addOverlay(geodesic)
                    }
                }
            }
        }

委托方法:

  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay.isKind(of: MKPolyline.self){
                var polylineRenderer = MKPolylineRenderer(overlay: overlay)
                polylineRenderer.fillColor = UIColor.blue
                polylineRenderer.strokeColor = UIColor.blue
                polylineRenderer.lineWidth = 2

            return polylineRenderer
     }
        return MKOverlayRenderer(overlay: overlay)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接