diff options
author | Jakub Hampl <kopomir@gmail.com> | 2018-07-13 15:20:50 +0100 |
---|---|---|
committer | Jakub Hampl <kopomir@gmail.com> | 2018-07-13 15:20:50 +0100 |
commit | cc6d143dd8124e13059c26125e70237795e9a9a4 (patch) | |
tree | e7d6a658990046b672bb59e6d97912e26b5fe057 /src/LngLat.elm | |
parent | 181401c4ffd06c127c57e27e2e88b05f7fdd1f88 (diff) |
Clean up various messes
Diffstat (limited to 'src/LngLat.elm')
-rw-r--r-- | src/LngLat.elm | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/LngLat.elm b/src/LngLat.elm new file mode 100644 index 0000000..896dc73 --- /dev/null +++ b/src/LngLat.elm @@ -0,0 +1,58 @@ +module LngLat exposing (LngLat, encodeAsPair, encodeAsObject, decodeFromPair, decodeFromObject, map) + +{-| @docs LngLat, encodeAsPair, encodeAsObject, decodeFromPair, decodeFromObject, map +-} + +import Json.Encode as Encode exposing (Value) +import Json.Decode as Decode exposing (Decoder) + + +{-| A LngLat represents a geographic position. +-} +type alias LngLat = + { lng : Float + , lat : Float + } + + +{-| Most implementations seem to encode these as a 2 member array. +-} +encodeAsPair : LngLat -> Value +encodeAsPair { lng, lat } = + Encode.list [ Encode.float lng, Encode.float lat ] + + +{-| Most implementations seem to encode these as a 2 member array. +-} +decodeFromPair : Decoder LngLat +decodeFromPair = + Decode.list Decode.float + |> Decode.andThen + (\l -> + case l of + [ lng, lat ] -> + Decode.succeed (LngLat lng lat) + + _ -> + Decode.fail "Doesn't apear to be a valid lng lat pair" + ) + + +{-| We can also encode as an `{lng: 32, lat: 435}` object. +-} +encodeAsObject : LngLat -> Value +encodeAsObject { lng, lat } = + Encode.object [ ( "lng", Encode.float lng ), ( "lat", Encode.float lat ) ] + + +{-| We can also encode from an `{lng: 32, lat: 435}` object. +-} +decodeFromObject : Decoder LngLat +decodeFromObject = + Decode.map2 LngLat (Decode.field "lng" Decode.float) (Decode.field "lat" Decode.float) + + +{-| -} +map : (Float -> Float) -> LngLat -> LngLat +map f { lng, lat } = + { lng = f lng, lat = f lat } |