gpt4 book ai didi

ios - objective-c MKMapView 以用户位置为中心

转载 作者:IT王子 更新时间:2023-10-29 07:46:22 25 4
gpt4 key购买 nike

我正在尝试放大用户位置作为屏幕的中心引用。我有这段代码:

MainViewController.h

#import <UIKit/UIKit.h>
#import "FlipsideViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

IBOutlet MKMapView *mapView;

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, MKMapViewDelegate> {
MKMapView *mapView;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapView;

MainViewController.m

@implementation MainViewController
@synthesize mapView;

- (void)viewDidLoad {
[super viewDidLoad];
mapView = [[MKMapView alloc]
initWithFrame:self.view.bounds
];
mapView.showsUserLocation = YES;
mapView.mapType = MKMapTypeHybrid;
mapView.delegate = self;
[self.view addSubview:mapView];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.005;
span.longitudeDelta = 0.005;
CLLocationCoordinate2D location;
location.latitude = userLocation.coordinate.latitude;
location.longitude = userLocation.coordinate.longitude;
region.span = span;
region.center = location;
[mapView setRegion:region animated:YES];
}

现在我只在最后一行 [mapView setRegion:region animated:YES] 上收到构建警告,指出:“'mapView' 的局部声明隐藏了实例变量”

最佳答案

当您执行 mapView.showsUserLocation = YES; 时,您要求它检索用户位置。这不会立即发生。由于需要时间, map View 通过委托(delegate)方法通知其委托(delegate)用户位置可用 mapView:didUpdateUserLocation .因此,您应该采用 MKMapViewDelegate 协议(protocol)并实现该方法。您应该将所有放大代码移至此方法。

设置委托(delegate)

- (void)viewDidLoad {
[super viewDidLoad];
mapView = [[MKMapView alloc]
initWithFrame:CGRectMake(0,
0,
self.view.bounds.size.width,
self.view.bounds.size.height)
];
mapView.showsUserLocation = YES;
mapView.mapType = MKMapTypeHybrid;
mapView.delegate = self;
[self.view addSubview:mapView];
}

更新委托(delegate)方法

- (void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)aUserLocation {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.005;
span.longitudeDelta = 0.005;
CLLocationCoordinate2D location;
location.latitude = aUserLocation.coordinate.latitude;
location.longitude = aUserLocation.coordinate.longitude;
region.span = span;
region.center = location;
[aMapView setRegion:region animated:YES];
}

关于ios - objective-c MKMapView 以用户位置为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com