我在 map View 中有一个初始放置的图钉。
我想要完成的是将该图钉拖到 map 内的任何位置并从该图钉获取新坐标。怎么做?我应该添加什么?
我有这个方法来做初始放置 pin。
- (void) performSearch
{
MKLocalSearchRequest *request =
[[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = _searchString;
request.region = _mapView.region;
_matchingItems = [[NSMutableArray alloc] init];
MKLocalSearch *search =
[[MKLocalSearch alloc]initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse
*response, NSError *error) {
if (response.mapItems.count == 0)
NSLog(@"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
[_matchingItems addObject:item];
annotation = [[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.name;
[_mapView addAnnotation:annotation];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance (annotation.coordinate, 800, 800);
[_mapView setRegion:region animated:NO];
}
}];
}
最佳答案
首先,符合MKMapViewDelegate
//ViewController.m
@interface ViewController () <MKMapViewDelegate>
@end
然后,将 map View 的委托(delegate)设置为self
-(void)viewDidLoad {
[super viewDidLoad];
_mapView.delegate = self;
...
...
}
然后实现下面两个委托(delegate)方法。
第一个委托(delegate)方法返回与注解对象关联的 View ,并设置这个 View 为可拖动的,
第二种方法,处理注释 View 的拖动状态。
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation {
MKPinAnnotationView *pin = (MKPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:@"pin"];
if(!pin) {
pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reueseIdentifier:@"pin"];
} else {
pin.annotation = annotation;
}
pin.draggable = YES;
return pin;
}
这里我们请求一个标识符为@"pin"的MKPinAnnotationView
,
如果我们没有收到,我们就创建它。
然后我们将 View 设置为可拖动。
以上内容足以移动并因此更改注释的坐标。
如果你想在设置新坐标时调用一些方法,你可以使用第二个委托(delegate)方法 -
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {
{
if(newState == MKAnnotationViewDragStateStarting) {
NSLog(@"%f, %f", view.annotation.coordinate.latitude, view.annotation.coordinate.longitude);
}
if(newState == MKAnnotationViewDragStateEnding) {
NSLog(@"%f, %f", view.annotation.coordinate.latitude, view.annotation.coordinate.longitude);
// Here you can call whatever you want to happen when to annotation coordinates changes
}
}
在这里您可以确定拖动何时真正结束,然后您可以调用任何您喜欢的方法来处理新坐标。
请注意,当拖动开始和结束时,我还包含了一个 NSLog
调用。
这只是为了调试目的,所以您会看到坐标实际上正在改变。
祝你好运。
关于ios - 如何在 map View 中拖动注释图钉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26826447/