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

 ̄綄美尐妖づ 提交于 2019-12-07 12:03:29

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.

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