how to make mapview zoom to 5 mile radius of current location

后端 未结 3 1785
盖世英雄少女心
盖世英雄少女心 2020-12-23 14:34

I know its a very common issue but I am not getting the exact answer for this thing.

How to make MKMapView defaults to a zoom of a 5 mile radius of current location.

3条回答
  •  悲哀的现实
    2020-12-23 15:26

    Use the MKCoordinateRegionMakeWithDistance function from MapKit.

    Use a conversion function to convert miles to meters since MapKit uses meters.

    float MilesToMeters(float miles) {
        // 1 mile is 1609.344 meters
        // source: http://www.google.com/search?q=1+mile+in+meters
        return 1609.344f * miles;
    }
    

    Then in your code set the map region as (thanks to @DylanBettermann for pointing out that to get a radius of 5 miles, the distance needs to be doubled)

    mapView.region = MKCoordinateRegionMakeWithDistance(
        centerCoordinate, 
        MilesToMeters(10.0f),
        MilesToMeters(10.0f)
    );
    

    swift 4 version :

    mapView.region = MKCoordinateRegion(
                center: centerCoordinate,
                latitudinalMeters: MilesToMeters(10.0f),
                longitudinalMeters: MilesToMeters(10.0f)
    )
    

提交回复
热议问题