Подтвердить что ты не робот

Нарисуйте круг радиусом 1000 м вокруг местоположения пользователей в MKMapView

(Использование iOS 5 и Xcode 4.2)

У меня есть MKMapView и вы хотите нарисовать круг радиуса 1000 м вокруг местоположения пользователя.

На первый взгляд кажется, что реализация mapView: viewForAnnotation: метода отображения вида карты и добавление пользовательского MKAnnotationView для местоположения пользователей, было бы идеальным решением. Он будет выглядеть примерно так:

- (MKAnnotationView *)mapView:(MKMapView *)mapView
            viewForAnnotation:(id <MKAnnotation>)annotation
{
    // If it the user location, return my custom MKAnnotationView.
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return myCustomAnnotationView;
    } else {
        return nil;
    }
}

Однако аннотации на карте не масштабируются при увеличении и удалении карты.

Итак, я попробовал добавить наложение (потому что накладывал масштаб с помощью карты), используя класс MKCircle и установив его координаты последние координаты с моего делегата locationManger/map view. Однако, поскольку свойство координат MKCircle выполняется только для чтения, мне нужно удалить оверлей, а затем добавить новый каждый раз, когда пользователь перемещается. Вызывает заметное мерцание, как это бывает.

Есть ли способ сделать шкалу аннотаций легко, так как масштабирование и изменение масштаба карты? Или есть хороший способ сделать плавный переход с изменениями в местоположении пользователей?

Буду очень признателен вам за помощь:)

4b9b3361

Ответ 1

Попробуйте пользовательский оверлей. Добавьте это в viewDidLoad:

MKCircle *circle = [MKCircle circleWithCenterCoordinate:userLocation.coordinate radius:1000];
[map addOverlay:circle];

userLocation можно получить, сохранив MKUserLocationAnnotation как свойство. Затем, чтобы нарисовать круг, поместите его в делегат представления карты:

- (MKOverlayRenderer *)mapView:(MKMapView *)map viewForOverlay:(id <MKOverlay>)overlay
{
    MKCircleRenderer *circleView = [[MKCircleRenderer alloc] initWithOverlay:overlay];
    circleView.strokeColor = [UIColor redColor];
    circleView.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.4];
    return circleView;
}

Ответ 2

Обновленная версия для iOS 8.0 с использованием Swift.

import Foundation
import MapKit

class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate{
    var locationManager: CLLocationManager = CLLocationManager()

    @IBOutlet var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // We use a predefined location
        var location = CLLocation(latitude: 46.7667 as CLLocationDegrees, longitude: 23.58 as CLLocationDegrees)

        addRadiusCircle(location)
    }

    func addRadiusCircle(location: CLLocation){
        self.mapView.delegate = self
        var circle = MKCircle(centerCoordinate: location.coordinate, radius: 10000 as CLLocationDistance)
        self.mapView.addOverlay(circle)
    }

    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        if overlay is MKCircle {
            var circle = MKCircleRenderer(overlay: overlay)
            circle.strokeColor = UIColor.redColor()
            circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1)
            circle.lineWidth = 1
            return circle
        } else {
            return nil
        }
    }
}

Ответ 3

Swift 3/Xcode 8 здесь:

func addRadiusCircle(location: CLLocation){
    if let poll = self.selectedPoll {
        self.mapView.delegate = self
        let circle = MKCircle(center: location.coordinate, radius: 10)
        self.mapView.add(circle)
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKCircle {
        let circle = MKCircleRenderer(overlay: overlay)
        circle.strokeColor = UIColor.red
        circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1)
        circle.lineWidth = 1
        return circle
    } else {
        return MKPolylineRenderer()
    }
}

Затем вызовите так:

self.addRadiusCircle(location: CLLocation(latitude: YOUR_LAT_HERE, longitude: YOUR_LNG_HERE))

Ответ 5

Я не понял ответ benwad. Так вот более ясный ответ:

Довольно легко добавить круг. Соответствует MKMapViewDelegate

@interface MyViewController : UIViewController <MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end

В viewDidLoad, создайте аннотацию круга и добавьте ее на карту:

CLLocationCoordinate2D center = {39.0, -74.00};

// Add an overlay
MKCircle *circle = [MKCircle circleWithCenterCoordinate:center radius:150000];
[self.mapView addOverlay:circle];

Затем выполните mapView: viewForOverlay: чтобы вернуть представление.

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    MKCircleView *circleView = [[MKCircleView alloc] initWithOverlay:overlay];
    [circleView setFillColor:[UIColor redColor]];
    [circleView setStrokeColor:[UIColor blackColor]];
    [circleView setAlpha:0.5f];
    return circleView;
}

Но если вы хотите, чтобы круг всегда был того же размера, независимо от уровня масштабирования, вам придется делать что-то другое. Как вы говорите, в regionDidChange: animated:, получите latitudeDelta, затем создайте новый круг (с радиусом, который вписывается в ширину), удалите старый и добавьте новый.

Обратите внимание: не забудьте связать mapview с делегатом контроллера вида. В противном случае viewForOverlay не будет вызываться.

Ответ 6

Легко добавить круг. Соответствует MKMapViewDelegate. следуйте нижеуказанным шагам,,

Шаг 1:

 CLLocationCoordinate2D center= {self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude};
// Add an overlay
MKCircle *circle= [MKCircle circleWithCenterCoordinate:center radius: 20000];//your distance like 20000(like meters)
[myMapView addOverlay:circle];

Шаг 2:

 - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
 {
    MKCircleView *C_View = [[MKCircleView alloc] initWithOverlay:overlay];
    [C_View setFillColor:[UIColor lightGrayColor]];
    [C_View setStrokeColor:[UIColor blackColor]];
    [C_View setAlpha:0.5f];

    return C_View;
 }

Ответ 7

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay

он устарел, поскольку iOS 4.0

Ответ 8

Используя MKCircleRenderer, вы можете добавить его следующим образом.

Объявить переменные уровня класса для наложения и его рендерера:

MKCircle circleOverlay;
MKCircleRenderer circleRenderer;

Внедрите MKMapView.OverlayRenderer, чтобы предоставить средство визуализации для наложения:

mapView.OverlayRenderer = (m, o) => {
    if(circleRenderer == null) {
        circleRenderer = new MKCircleRenderer(o as MKCircle);
        circleRenderer.FillColor = UIColor.Green;
        circleRenderer.Alpha = 0.5f;
    }
    return circleRenderer;
};

Создайте наложение, в этом случае круг, расположенный рядом с местоположением пользователя (широта, долгота) и добавьте его на карту:

var coords = new CLLocationCoordinate2D(39.11, 30.13); //user location
circleOverlay = MKCircle.Circle (coords, 1000);
mapView.AddOverlay (circleOverlay);