jjzjj

ios - MKPolyline 未显示在 MKMapView 上

coder 2024-01-20 原文

这是代码。它非常简单。我正在为走路的人开路。 所以,这是我的 ViewController.m 文件的代码:

#import "ViewController.h"

@interface ViewController ()

@property BOOL firstTime;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.mapView setDelegate:self];
    [self.mapView setShowsUserLocation:YES];
    [self.mapView setMapType:MKMapTypeHybrid];

    [self setLocationManager:[[CLLocationManager alloc] init]];
    [self.locationManager setDelegate:self];
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager startUpdatingLocation];

    self.index = 0;

    self.firstTime = YES;
}

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

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    if(self.firstTime)
    {
        CLLocation *startingLocation = [locations objectAtIndex:0];
        self.startingPointCooridinates = startingLocation.coordinate;
        self.index++;

        MKPointAnnotation *startingPointAnnotation = [[MKPointAnnotation alloc] init];
        startingPointAnnotation.title = @"Starting Point";
        startingPointAnnotation.coordinate = startingLocation.coordinate;

        [self.mapView addAnnotation:startingPointAnnotation];

        self.firstTime = false;
    }

    [self.locations addObject:[locations objectAtIndex:0]];

    CLLocationCoordinate2D coordinates[[self.locations count]];
    for(int i = 0; i < self.locations.count; i++)
    {
        CLLocation *currentLocation = [locations objectAtIndex:i];
        coordinates[i] = currentLocation.coordinate;
    }

    MKPolyline *pathPolyline = [MKPolyline polylineWithCoordinates:coordinates count:self.locations.count];
    [self.mapView addOverlay:pathPolyline];
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    if([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *polylineRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        polylineRenderer.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
        polylineRenderer.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.7];
        polylineRenderer.lineWidth = 2.0;
        return polylineRenderer;
    }
    else
    {
        return  nil;
    }
}

现在,只显示注释,没有显示任何 MKPolyline。我究竟做错了什么 ?谢谢。

最佳答案

  1. 如评论中所述,您的 locations 数组从未分配和初始化,因此它是 nil 并调用它(如 addObject) 什么都不做,因此多段线永远不会添加任何坐标(因此它不会显示)。

    viewDidLoad 中,在启动 CLLocationManager 之前,分配并初始化数组:

    self.locations = [NSMutableArray array];
    
  2. 您将遇到的另一个问题是 for 循环中 didUpdateLocations 中的这一行:

    CLLocation *currentLocation = [locations objectAtIndex:i];
    

    这里,locations(没有self.)指的是委托(delegate)方法的局部参数变量,而不是您的位置 类实例级属性变量。编译器必须通过类似“'locations' 的局部声明隐藏实例变量”的消息警告您这一点。

    在这种情况下,警告很严重。您在这里真正想做的是引用 locations 属性变量,您在其中存储用户的完整坐标轨迹,而不是仅具有最后 x 个未报告位置的局部变量(通常只有 1 个对象).

    因此该行应更改为:

    CLLocation *currentLocation = [self.locations objectAtIndex:i];
    

    最好使用与 locations 不同的名称来避免这些问题。

  3. 正如评论中所提到的,由于每次用户移动时您都在添加一个包含用户完整运动轨迹的叠加层,因此您需要先删除之前的叠加层。否则,您将不必要地向 map 添加多个叠加层,因为最后一个叠加层覆盖了整个运动。之前的叠加层不明显可见,因为它们具有相同的坐标、相同的颜色和相同的线宽。因此,在调用 addOverlay 之前,最简单的做法是使用 map 的当前叠加层列表调用 removeOverlays:

    //remove any previous overlays first...
    [self.mapView removeOverlays:mapView.overlays];
    
    //now add overlay with the updated trail...
    [self.mapView addOverlay:pathPolyline];
    
  4. 不影响显示的一个小问题是为折线设置 fillColor 没有效果。您只需要设置代码正在执行的 strokeColor 即可。您可以删除设置 fillColor 的调用。

  5. 最后,您可能有兴趣查看 Apple's Breadcrumb sample app .他们的版本使用自定义覆盖层,可以动态更新,而无需在每次更改或添加时删除和添加覆盖层。

关于ios - MKPolyline 未显示在 MKMapView 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20721190/

有关ios - MKPolyline 未显示在 MKMapView 上的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  4. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  5. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  6. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  7. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  8. ruby-on-rails - 复数 for fields_for has_many 关联未显示在 View 中 - 2

    目前,Itembelongs_toCompany和has_manyItemVariants。我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不显示该表单。只有当我使用单数时才会显示。我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?提前致谢。注意:下面的代码片段中省略了不相关的代码。编辑:不知道这是否相关,但我正在使用CanCan进行身份验证。routes.rbresources:companiesdoresources:itemsenditem.rbclassItemi

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. ruby-on-rails - 在 Flash 警报 Rails 3 中显示错误消息 - 2

    如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]

随机推荐