Reputation: 2765
I'm trying to figure out a straightforward way to determine in Google Maps for iOS if a given GMSMarker is within the bounds of the visible map. There seems to be solutions for this in the Javascript API but other than perhaps doing some complex reasoning based on this post there doesn't seem to be a way.
Upvotes: 12
Views: 7783
Reputation: 754
The swift 4 version of the answer. Returning a boolean if marker is within the screen region or not
func isMarkerWithinScreen(marker: GMSMarker) -> Bool {
let region = self.mapView.projection.visibleRegion()
let bounds = GMSCoordinateBounds(region: region)
return bounds.contains(marker.position)
}
Upvotes: 10
Reputation: 11534
I have written on method to find GMSMarker is in particular frame. Set your rectangle frame (x,y,maxX,maxY). You can set any frame from screen it tell find marker is in that frame or not..
- (BOOL)isGoogleMapMarkerVisible:(GMSMarker*)marker {
//Marker point
CGPoint markerpoint = [self.mapview.projection pointForCoordinate:marker.position];
//Maximum visible region from x and y axis
float x = 0.0;
float y = o.o;
float maxX = self.mapview.frame.size.width;
float maxY = self.mapview.frame.size.height;
//If marker point is on visible region return true else return false
if (markerpoint.x > x && markerpoint.y > y && markerpoint.x < maxX && markerpoint.y < maxY) {
return YES;
}
else {
return NO;
}
}
Upvotes: 1
Reputation: 5023
Hope this code may help to code hunters.
NSMutableArray *mutArrMarkers; //Have all markers added on Map
.
.
.
.
NSMutableArray *mutArrMarkersInPath = [NSMutableArray array];
[mutArrMarkers enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
GMSMarker *marker = obj;
if(GMSGeometryContainsLocation(currentCoordinates, pathToCheck, YES)){
[mutArrMarkersInPath addObject:marker];
}
}];
Upvotes: 0
Reputation: 2765
A code example based on Andy's helpful response:
- (void)snapToMarkerIfItIsOutsideViewport:(GMSMarker *)m{
GMSVisibleRegion region = _mapView.projection.visibleRegion;
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithRegion:region];
if (![bounds containsCoordinate:m.position]){
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:m.position.latitude
longitude:m.position.longitude
zoom:_mapView.camera.zoom];
[self.mapView animateToCameraPosition: camera];
}
}
Upvotes: 18
Reputation: 2414
Retrieve the bounds of your viewport with GMSVisibleRegion and create a GMSCoordinateBounds with it. Call containsCoordinate
, passing in the marker's position. It should return true if the marker is within the viewport and false if not.
Upvotes: 16