How to zoom Mapbox using Swift to a given radius in kilometers?

本秂侑毒 提交于 2019-12-10 22:47:36

问题


I recently updated from legacy Mapbox SDK (version 1.6) to latest Mapbox iOS SDK 3.x.

In new version I am not able to figure out how to zoom Mapbox MGLMapView to a given radius in kilometers to fit on screen.

In old (version 1.6) RMMapView.zoomWithLatitudeLongitudeBoundsSouthWest method does the job as following:

func centerAndZoom(center: CLLocationCoordinate2D, kilometers: Float) {
    let meters = Double(kilometers * 1000)
    let region = MKCoordinateRegionMakeWithDistance(center, meters / 2, meters / 2);

    let northEastLat = center.latitude - (region.span.latitudeDelta / 2);
    let northEastLon = center.longitude + (region.span.longitudeDelta / 2);
    let northEast = CLLocationCoordinate2D(latitude: northEastLat, longitude: northEastLon)

    let southEastLat = center.latitude + (region.span.latitudeDelta  / 2);
    let southEastLon = center.longitude - (region.span.longitudeDelta / 2);
    let southEast = CLLocationCoordinate2D(latitude: southEastLat, longitude: southEastLon)

    self.mapView.zoomWithLatitudeLongitudeBoundsSouthWest(southEast, northEast: northEast, animated: true)
}

How to achieve a radius zoom in latest Mapbox using Swift?


回答1:


Now -setVisibleCoordinateBounds:animated will do the job:

Changes the receiver’s viewport to fit the given coordinate bounds, optionally animating the change.

Mapbox iOS SDK Reference

Here is an example:

let bounds = MGLCoordinateBounds(
        sw: CLLocationCoordinate2D(latitude: 43.7115, longitude: 10.3725),
        ne: CLLocationCoordinate2D(latitude: 43.7318, longitude: 10.4222))
mapView.setVisibleCoordinateBounds(bounds, animated: false)



回答2:


Here is how I made zoom to specific radius from given coordinate:

let center = CLLocationCoordinate2D(latitude: <#T##CLLocationDegrees#>, longitude: <#T##CLLocationDegrees#>)
let kilometers: Double = 2.0
let halfMeters = (kilometers * 1000) / 2
let region = MKCoordinateRegionMakeWithDistance(center, halfMeters, halfMeters)
let southWest = CLLocationCoordinate2D(
    latitude: center.latitude - (region.span.latitudeDelta  / 2),
    longitude: center.longitude - (region.span.longitudeDelta / 2)
)
let northEast = CLLocationCoordinate2D(
    latitude: center.latitude + (region.span.latitudeDelta  / 2),
    longitude: center.longitude + (region.span.longitudeDelta / 2)
)

let bounds = MGLCoordinateBounds(sw: southWest, ne: northEast)
mapView.setVisibleCoordinateBounds(bounds, edgePadding: .zero, animated: false)


来源:https://stackoverflow.com/questions/38946722/how-to-zoom-mapbox-using-swift-to-a-given-radius-in-kilometers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!