Is it possible to set a fixed on-screen position for the User Location Pin on MKMapView?

旧城冷巷雨未停 提交于 2019-12-08 08:54:09

问题


I'm trying to set up a MKMapView in a way that the user's location would always be offset in the top right corner of the view controller, and I would build the rest of my UI around that "block".

Is there a way to set a fixed/offset center point for the MKMapView for example in a way that the pin is always at an x, y position on the screen?

I can provide a sketched example if you are having trouble understanding my goal.


回答1:


I figured it out just now,

func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
    // Define a span (for zoom)
    let span: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)

    // Get user location
    let location = CLLocationCoordinate2D(
      latitude: userLocation.coordinate.latitude,
      longitude: userLocation.coordinate.longitude
    )

    // Get the close region for the user's location
    // This zooms into the user's tracked location
    let region = MKCoordinateRegion(center: location, span: span)
    let adjusted = mapView.regionThatFits(region)
    mapView.setRegion(adjusted, animated: true)

    // Here we set the offset of the map to be 75% to the right
    // and 15% from the top. Gives us a nice top right view.
    var rect = mapView.visibleMapRect
    let point = MKMapPointForCoordinate(location)
    rect.origin.x = point.x - rect.size.width * 0.75
    rect.origin.y = point.y - rect.size.height * 0.15
    mapView.setVisibleMapRect(rect, animated: true)
}

Pablo A.'s answer was a good starting point, but sadly it wasn't enough to do what I was looking for.

I went ahead and added a mask view on top of the map view as well to better visualize what kind of UI I was going for in the end.




回答2:


You can convert the pixel coordinates to map coordinates in order to know where to add your pin, and update it every time the map region is changed:

CGPoint fakecenter = CGPointMake(20, 20);
CLLocationCoordinate2D coordinate = [mapView convertPoint:fakecenter toCoordinateFromView:mapView];


来源:https://stackoverflow.com/questions/32501846/is-it-possible-to-set-a-fixed-on-screen-position-for-the-user-location-pin-on-mk

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