Getting the bounds of an MKMapView

前端 未结 10 1115
既然无缘
既然无缘 2020-11-28 20:28

In order to setup a query to an external server I want to get the bounds of the current Map View in an iPhone app I\'m building. UIView should respond to bounds but it seems

10条回答
  •  我在风中等你
    2020-11-28 20:42

    This http://wiki.openstreetmap.org/wiki/Bounding_Box is a document for bounding box

    bbox = left,bottom,right,top
    bbox = min Longitude , min Latitude , max Longitude , max Latitude
    

    You can have a BoundingBox struct that represents this

    struct BoundingBox {
      let min: CLLocationCoordinate2D
      let max: CLLocationCoordinate2D
    
      init(rect: MKMapRect) {
        let bottomLeft = MKMapPointMake(rect.origin.x, MKMapRectGetMaxY(rect))
        let topRight = MKMapPointMake(MKMapRectGetMaxX(rect), rect.origin.y)
    
        min = MKCoordinateForMapPoint(bottomLeft)
        max = MKCoordinateForMapPoint(topRight)
      }
    
      var points: [CLLocationDegrees] {
        return [
          min.latitude,
          min.longitude,
          max.latitude
          max.longitude,
        ]
      }
    }
    

    The visibleMapRect is the same as region.span

    let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: 320, height: 640))
    XCTAssertEqual(mapView.userLocation.coordinate.latitude, 0)
    XCTAssertEqual(mapView.userLocation.coordinate.longitude, 0)
    
    let boundingBox = BoundingBox(rect: mapView.visibleMapRect)
    XCTAssertEqual(boundingBox.max.longitude-boundingBox.min.longitude, mapView.region.span.longitudeDelta)
    XCTAssertEqual(boundingBox.max.latitude-boundingBox.min.latitude, mapView.region.span.latitudeDelta)
    

提交回复
热议问题