11

I am trying to determine the marker/s currently shown in a mapview. I have researched the following the method:

self.mapView.bounds.contains(markers[0].position)

But the contains command accepts CGPoint or CGRect. In other platforms except Swift, contains can accept the marker's position.

How do I convert the marker's position to be accepted by contains?

Jayson Tamayo
  • 2,741
  • 3
  • 49
  • 76

2 Answers2

9

Use the mapview's current projection. Use the projection's method called containsCoordinate to check if you marker's position is inside the projection, i.e. currently visible.

So something like:

let coord = marker.position
let isVisible = self.mapview.projection.containsCoordinate(coord)

https://developers.google.com/maps/documentation/ios-sdk/reference/interface_g_m_s_projection.html#aa6ad29e6831e40f00435c3aaeda8e08a

Juul
  • 642
  • 4
  • 18
  • Alternatively, you can try to convert the marker's positions to screen points using the projection too. – Juul Sep 18 '16 at 10:08
  • My marker is inside the map but few portion of marker is outside the map. How could I know that? I have tried using projection to convert the lat long to screen point but sometimes it gives me negative value. Can you have a working sample code of projection? – Nimisha Patel Apr 04 '18 at 16:35
2

In MapKit:

I assume with Marker you mean an MKAnnotation. Instead of using the bounds of the mapView you should use the visibleMapRect and see if it contains the coordinates of the Marker in MKMapPoints. This is the code I used:

let markerPoint = MKMapPointForCoordinate(markers[0].coordinate)
if MKMapRectContainsPoint(mapView.visibleMapRect, markerPoint) {
    print("Found")
} else {
    print("Not found")
}

Only when the coordinates of the markers are visible (in other words, the marker is being displayed), this will print "Found". If off-screen, it will print "Not found".

Christoph
  • 702
  • 6
  • 16
  • I just realised that you tagged "google-maps-sdk-ios", I was referring to `MapKit`. Sorry about that. Please make it clear in your question since both APIs are very similar. – Christoph Sep 17 '16 at 16:49