5
votes

The following function is called when the user moved the map.

It is possible to get the viewport? Viewport is latitude and longitude of north/east and the lat. and lon. of south/west.

 func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool){
    print("The \(mapView.centerCoordinate)")
    print("the maprect \(mapView.visibleMapRect.origin)")
    print("the maprect \(mapView.visibleMapRect.size)")
    //I find just this attributes for mapView

    }

I don't know how get the viewports out of my data. I can't find anything in the www.

The destination is that I log the coordinates with google analytics and another tool evaluate the datas.

Has somebody an idea? Thanks a lot

2

2 Answers

11
votes

MapKit

let northEast = mapView.convertPoint(CGPoint(x: mapView.bounds.width, y: 0), toCoordinateFromView: mapView)
let southWest = mapView.convertPoint(CGPoint(x: 0, y: mapView.bounds.height), toCoordinateFromView: mapView)

googleMaps

mapView has a property "projection" where you can use "coordinateForPoint" to convert a point from the mapView to a coordinate. so the following could work:

swift 3 for google maps

let northEast = mapView.projection.coordinate(for: CGPoint(x: mapView.layer.frame.width, y: 0))
let southWest = mapView.projection.coordinate(for: CGPoint(x: 0, y: mapView.layer.frame.height))

swift 2

let northEast = mapView.projection.coordinateForPoint(CGPoint(x: mapWidth, y: 0 ))
let southWest = mapView.projection.coordinateForPoint(CGPoint(x: 0, y: mapHeight))

you just need to enter your mapView width and height

4
votes

Based on fel1xw answer

Swift 3 MapKit

let northEast = mapView.convert(CGPoint(x: mapView.bounds.width, y: 0), toCoordinateFrom: mapView)
let southWest = mapView.convert(CGPoint(x: 0, y: mapView.bounds.height), toCoordinateFrom: mapView)