How to get the latitude and longtitude in the center of view.map (Xamarin.Forms.Maps) when region changed?

461 Views Asked by At

Please comment, how to get the latitude and longitude in the center of map (Xamarin.Forms.Maps) when region changed? In C#, retrieve the property "Map.VisibleRegion"(https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.maps.map.visibleregion?view=xamarin-forms) and find a related property "MapSpan.Center". However, it isn't same as F# with fabulous, I don't know how to retrieve property from view.map. Thank you.

let view (model : Model) dispatch =
    let paris = Position(48.8566, 2.3522)
    let london = Position(51.5074, -0.1278)
    let calais = Position(50.9513, 1.8587)

    let map =
        View.Map
            (hasZoomEnabled = true, hasScrollEnabled = true,
             pins = [ View.Pin(paris, label = "Paris", pinType = PinType.Place)
                      View.Pin(london, label = "London", pinType = PinType.Place) ],
             requestedRegion = MapSpan.FromCenterAndRadius(calais, Distance.FromKilometers(300.0)))
    // View
    View.ContentPage(content = map)
    -- e.g map.visibleRegion
1

There are 1 best solutions below

0
On

Base on the comment (https://github.com/fsprojects/Fabulous/issues/635) from Tim Lariviere, the problem has been resolved. Thank you.

let mapRef = ViewRef<Map>()

......
let tryGetCameraPosition() =
        match mapRef.TryValue with 
                          | None -> Some (0.0, 0.0) |> Option.map (fun l -> CameraPositionRetrieved(l))
                          | Some obj -> 
                                let map = obj :?> Xamarin.Forms.Maps.Map
                                let c = map.VisibleRegion.Center
                                Some (c.Latitude, c.Longitude) |> Option.map (fun l -> CameraPositionRetrieved(l))
......
let update msg model =
    match msg with
    | UpdateCameraPosition  -> 
        let msg = tryGetCameraPosition()
        model, Cmd.ofMsgOption msg
    | CameraPositionRetrieved location -> { model with CameraPosition = Some location }, Cmd.none

......
let view (model : Model) dispatch =
......
View.Map(hasZoomEnabled = true, hasScrollEnabled = true, ref = mapRef,