Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get viewport coordinates from mapView? regionDidChanged swift

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

like image 692
kuzdu Avatar asked Apr 07 '16 12:04

kuzdu


2 Answers

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

like image 103
fel1xw Avatar answered Nov 06 '22 03:11

fel1xw


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)
like image 4
user2213459 Avatar answered Nov 06 '22 03:11

user2213459