今天发现自己好笨啊。。。一直在搞定位,想为什么会是空的,原来定位也是需要代理去实现的
在初始化地图的时候,也就是在viewDidload里面是这样的
[java] view plaincopyprint?
- mapView.showsUserLocation
= YES; - if
(mapView.userLocation.location != nil) -
{ -
NSLog(@"定位成功"); -
coor = [[mapView.userLocation location] coordinate]; -
NSLog(@"%f",coor.latitude); -
NSLog(@"%f",coor.longitude); -
} -
BMKCoordinateRegion viewRegion = BMKCoordinateRegionMake(coor, BMKCoordinateSpanMake(0.02f,0.02f)); -
BMKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion]; -
[mapView setRegion:adjustedRegion animated:YES];
mapView.showsUserLocation = YES; if (mapView.userLocation.location != nil) { NSLog(@"定位成功"); coor = [[mapView.userLocation location] coordinate]; NSLog(@"%f",coor.latitude); NSLog(@"%f",coor.longitude); } BMKCoordinateRegion viewRegion = BMKCoordinateRegionMake(coor, BMKCoordinateSpanMake(0.02f,0.02f)); BMKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion]; [mapView setRegion:adjustedRegion animated:YES];
一直以为是这样的呢,因为设定了showUserLocation 在去取到当前的userLocation就好了呢,这样做是不会立马就定位到的,它内部的实现是在子线程去定位,
然后通过代理方法去更新当前的用户位置的,好晕啊,仔细一找 ,就找到了这个更新用户当前位置的代理方法
-
- -
(void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation;
- (void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation;
那么就去实现它好了,这个时候应该是定位到了用户的位置了,也就是这个userLocation了
- #pragma
mark mapViewDelegate 代理方法 - -
(void)mapView:(BMKMapView *)mapView1 didUpdateUserLocation:(BMKUserLocation *)userLocation - {
-
BMKCoordinateRegion region; -
region.center.latitude = userLocation.location.coordinate.latitude; -
region.center.longitude = userLocation.location.coordinate.longitude; -
region.span.latitudeDelta = 0.2; -
region.span.longitudeDelta = 0.2; -
if (mapView) -
{ -
mapView.region = region; -
NSLog(@"当前的坐标是: %f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude); -
} - }
#pragma mark mapViewDelegate 代理方法 - (void)mapView:(BMKMapView *)mapView1 didUpdateUserLocation:(BMKUserLocation *)userLocation { BMKCoordinateRegion region; region.center.latitude = userLocation.location.coordinate.latitude; region.center.longitude = userLocation.location.coordinate.longitude; region.span.latitudeDelta = 0.2; region.span.longitudeDelta = 0.2; if (mapView) { mapView.region = region; NSLog(@"当前的坐标是: %f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude); } }
总结
实现定位必须
1.初始化mapview
2.设置mapview的showUserLocation的属性为YES
3.去实现didUpdateUserLocation代理来实现当前位置显示在可视范围内
小知识的积累,定是大财富的源泉。虚心学习,每天进步一点点。