Search code examples
iosmkmapviewmapkitcgpointcllocationcoordinate2d

MKMapView - mapView convertCoordinate: toPointToView: returns nan


I am trying to convert coordinate on an MKMapview to a cgpoint inside a view.

Here is what I am doing:

    CGPoint point = [map convertCoordinate:coord toPointToView:self.view];
    NSLog(@"lat = %f, lon = %f", coord.latitude, coord.longitude);
    NSLog(@"x = %f, y = %f", point.x, point.y);

The output that I am getting is:

lat = 243568961.394369, lon = 165303343.177200 x = nan, y = nan

I have viewed other questions on SO and this seems to be the correct way to go about it.

Hope you can help.

edit

I have just realised that the coordinate (coord) that is being logged is not the actual coordinates that I have intended.

Here is how I am getting this coordinate:

    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(tileOverlay.mapRect.origin.x, tileOverlay.mapRect.origin.y);

So I guess that problem is more with getting coordinates from the MKMapRect of MKTileOverlay.


Solution

  • Okay, so the problem was that I was trying to use MKMapPoint values to create a CLLocationCoordinate2D. Obviously this created an invalid coordinate. Here is what I did to fix it:

        MKMapPoint mp = MKMapPointMake(tileOverlay.mapRect.origin.x, tileOverlay.mapRect.origin.y);
    
        CLLocationCoordinate2D coord = MKCoordinateForMapPoint(mp);
    
        CGPoint point = [map convertCoordinate:coord toPointToView:self.view];
    

    and everything works as intended