如何获得MKMapView地图的中心?

Hay*_*ydn 16 iphone objective-c mkmapview

我有一个MKMapView,允许用户滚动地图.后来,我想得到地图中心点的纬度和经度,但找不到一个简单的方法.目前我正在尝试这样的事情:

CLLocationCoordinate2D centre = [locationMap convertPoint:locationMap.center toCoordinateFromView:locationMap];
txtLatitude.text = [NSString stringWithFormat:@"%f",centre.latitude];
txtLongitude.text = [NSString stringWithFormat:@"%f",centre.longitude];
Run Code Online (Sandbox Code Playgroud)

但它没有用 - 纬度和经度都是零.我会感激任何人可能有的想法!

==============

- 更新1 -

哦.如果我添加:

NSLog(@"%@", locationMap);
Run Code Online (Sandbox Code Playgroud)

如下所示,日志显示"(null)".我的标题中包括以下内容(除此之外):

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

IBOutlet MKMapView *locationMap;

@property (nonatomic, retain) IBOutlet MKMapView *locationMap;
Run Code Online (Sandbox Code Playgroud)

以及我的方法文件中的以下内容:

@synthesize locationMap;
Run Code Online (Sandbox Code Playgroud)

这是在编译时没有任何警告或错误.开始怀疑我是否错过了一些明显的东西?

dea*_*rne 46

怎么样centerCoordinate财产?

CLLocationCoordinate2D centre = [locationMap centerCoordinate];
Run Code Online (Sandbox Code Playgroud)

如果centerCoordindate属性全为0,请检查您是否有一个有效的locationMap指针 - objective-c将允许您将消息发送到nil而不会出现任何错误!

尝试NSLog(@"%@", locationMap);- 如果输出为nil,您可能忘记将mapLocation连接到Interface Builder中的MKMapView;)