本例是以高德地圖覆蓋物圓作為電子圍欄,通過給mapview添加的Tap事件確定圓的經緯度,滑動slider修改圓的半徑,來添加電子圍欄。
添加代理UIGestureRecognizerDelegate(為了解決點擊事件沖突)
- (void)viewDidLoad {
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
tap.delegate = self; //一定要記得設置代理
[self.mapView addGestureRecognizer:tap];
//獲取上次設置的圈的經緯度和半徑
self.circle = [MACircle circleWithCenterCoordinate:self.touchMapCoordinate radius:self.Rslider.value];
}
//允許多個交互事件
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
//點擊事件
- (void)tap:(UITapGestureRecognizer *)tap
{
//移除屏幕上的圓
[self.mapView removeOverlay:self.circle];
//保存點擊獲取的經緯度
self.touchMapCoordinate =
[self.mapView convertPoint:[tap locationInView:self.mapView] toCoordinateFromView:self.mapView];
//設置圓的位置
self.circle.coordinate = self.touchMapCoordinate;
//反地理編碼獲取詳細地址
[self getAddressByLatitude:self.touchMapCoordinate.latitude longitude:self.touchMapCoordinate.longitude];
//顯示經緯度及半徑
self.latitudeLb.text = [NSString stringWithFormat:@"%f", self.touchMapCoordinate.latitude];
self.longitudeLb.text = [NSString stringWithFormat:@"%f", self.touchMapCoordinate.longitude];
self.valueLabel.text = [NSString stringWithFormat:@"%.3f千米", self.Rslider.value/1000];
//添加新圓到屏幕上
[self.mapView addOverlay: self.circle];
}
//滑動slider改變圓的半徑(ValueChange)
- (IBAction)Rslider:(id)sender {
self.valueLabel.text = [NSString stringWithFormat:@"%.3f千米", self.Rslider.value/1000];
//移除屏幕上的圓
[self.mapView removeOverlay:self.circle];
self.circle = nil;
//設置圓的半徑(經緯度由點擊事件獲取)
self.circle = [MACircle circleWithCenterCoordinate:self.touchMapCoordinate radius:self.Rslider.value];
//添加新圓到屏幕上
[self.mapView addOverlay:self.circle];
}
最終效果