Search code examples
iosgoogle-mapspropertiesmarkercllocationcoordinate2d

Passing a property with coordinates in ios app


I am facing a problem in IOS with passing a property between different classes... So the problem is as follows:

I have a class called GMDraggableMarkerManager which allows me to drag a marker. All I want to do is to get the final coordinates of this marker, but I can't get the property passed to the ViewController where I want to use these coordinates as a center of a circle.

In the header of GMDraggableMarkerManager I declared a property(in the implementation file it gets coordinates where needed and I even see them in the console when run the app on the simulator):

@property (assign, nonatomic, readwrite) CLLocationCoordinate2D markerPosition;

In the header file of View Controller I imported this hedaer file, but it doesn't see it... So, I can't write the code like this:

CLLocationCoordinate2D circleCenter = _markerPosition; //Tried with just markerPosition as well.

The error I get is "Use of undeclared identifier 'markerPosition'.

I know this should be really stupid and easy to solve but I just don't get what I should do? If delegate or protocol, then how?


Solution

  • One way to do this is with the delegate pattern. In a nutshell...

    // GMDraggableMarkerManager.h
    @protocol GMDraggableMarkerManagerDelegate;
    
    @property(weak,nonatomic) id<GMDraggableMarkerManagerDelegate>delegate;
    
    @protocol GMDraggableMarkerManagerDelegate <NSObject>
    - (void)gMDraggableMarkerManager:(GMDraggableMarkerManager *)dmm didFinishDraggingAt:(CLLocationCoordinate2D)coord;
    @end
    
    // GMDraggableMarkerManager.m
    
        // somewhere in here, after dragging is complete
        // the last coordinate is coord
        [self.delegate gMDraggableMarkerManager:self didFinishDraggingAt:coord];
    

    The point of all that is, nobody get's to take the value of the last dragged coordinate from the draggable marker manager. It has a delegate, and it declares that it has the responsibility to inform it's delegate about the completion of a drag.

    Now you just need to get your view controller setup as a delegate.

    // in ViewController.m
    
    #import "GMDraggableMarkerManager.h"
    
    @interface ViewController () <GMDraggableMarkerManagerDelegate>
    // ...
    @end
    
    @implementation ViewController
    
    // not sure how you get a handle to the GMDraggableMarkerManager
    // maybe you create it here?
    
    // however you get it...
    GMDraggableMarkerManager *dmm = // however
    dmm.delegate = self;
    

    Finally, implement the delegate method (since you declared everything properly, the compiler will warn you that you claimed to implement a protocol if it can't find the methods).

    - (void)gMDraggableMarkerManager:(GMDraggableMarkerManager *)dmm didFinishDraggingAt:(CLLocationCoordinate2D)coord {
    
        NSLog(@"ta-da %f,%f", coord.latitude, coord.longitude);
    }