From cc6d143dd8124e13059c26125e70237795e9a9a4 Mon Sep 17 00:00:00 2001 From: Jakub Hampl Date: Fri, 13 Jul 2018 15:20:50 +0100 Subject: Clean up various messes --- src/Mapbox/Cmd.elm | 608 -------------------------------------------- src/Mapbox/Cmd/Internal.elm | 14 + src/Mapbox/Cmd/Option.elm | 188 ++++++++++++++ src/Mapbox/Cmd/Template.elm | 435 +++++++++++++++++++++++++++++++ src/Mapbox/Element.elm | 51 +--- src/Mapbox/Helpers.elm | 4 + src/Mapbox/Source.elm | 28 +- src/Mapbox/Style.elm | 7 +- 8 files changed, 673 insertions(+), 662 deletions(-) delete mode 100644 src/Mapbox/Cmd.elm create mode 100644 src/Mapbox/Cmd/Internal.elm create mode 100644 src/Mapbox/Cmd/Option.elm create mode 100644 src/Mapbox/Cmd/Template.elm (limited to 'src/Mapbox') diff --git a/src/Mapbox/Cmd.elm b/src/Mapbox/Cmd.elm deleted file mode 100644 index 17cea13..0000000 --- a/src/Mapbox/Cmd.elm +++ /dev/null @@ -1,608 +0,0 @@ -module Mapbox.Cmd exposing (Id, Outgoing, Option, Supported, duration, easing, offset, animate, panBy, panTo, zoomTo, zoomIn, zoomOut, rotateTo, jumpTo, easeTo, flyTo, curve, minZoom, speed, screenSpeed, maxDuration, stop, center, zoom, bearing, pitch, around, fitBounds, padding, Padding, linear, maxZoom, setRTLTextPlugin, Response, queryResults, getBounds, queryRenderedFeatures, Query, layers, filter, resize) - -{-| This module has a bunch of essentially imperative commands for your map. - -@docs Id, Outgoing - -However, since a published library can't have ports in it, you will need to do some setup. The easiest way to do this is to copy [this file into your app](https://github.com/gampleman/elm-mapbox/blob/master/examples/MapCommands.elm). - -@docs Option, Supported - - -### Animation options - -Options common to map movement commands that involve animation, such as panBy and easeTo, controlling the duration and easing function of the animation. All properties are optional. - -@docs duration, easing, offset, animate - - -### Moving the map around - -@docs panBy, panTo, zoomTo, zoomIn, zoomOut, rotateTo, jumpTo, easeTo, flyTo, curve, minZoom, speed, screenSpeed, maxDuration, stop - - -### Camera Options - -Options common to `jumpTo`, `easeTo`, and `flyTo`, controlling the desired location, zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current camera value for that property will remain unchanged. - -@docs center, zoom, bearing, pitch, around - - -### Fiting bounds - -@docs fitBounds, padding, Padding, linear, maxZoom - - -### Other - -@docs setRTLTextPlugin, resize - - -### Querying the map - -@docs Response, queryResults, getBounds, queryRenderedFeatures, Query, layers, filter - --} - -import Json.Decode as Decode -import Json.Encode as Encode exposing (Value) -import Mapbox.Element exposing (LngLat, Viewport) -import Mapbox.Expression exposing (DataExpression, Expression) - - -{-| The type of a port that you need to provide for this module to work. --} -type alias Outgoing msg = - Value -> Cmd msg - - -{-| Every command takes the DOM id of the map that it should operate on. --} -type alias Id = - String - - - --- AnimationOptions - - -{-| The animation's duration, measured in milliseconds. --} -duration : Int -> Option { a | duration : Supported } -duration = - Encode.int >> Option "duration" - - -{-| The name of an easing function. These must be passed to `elmMapbox` -in the `easingFunctions` option. --} -easing : String -> Option { a | easing : Supported } -easing = - Encode.string >> Option "easing" - - -{-| Offset of the target center relative to real map container center at the end of animation. --} -offset : ( Int, Int ) -> Option { a | offset : Supported } -offset = - encodePair Encode.int >> Option "offset" - - -{-| If false, no animation will occur. --} -animate : Bool -> Option { a | animate : Supported } -animate = - Encode.bool >> Option "animate" - - -{-| The desired center. --} -center : LngLat -> Option { a | center : Supported } -center = - encodePair Encode.float >> Option "center" - - -{-| The desired zoom level. --} -zoom : Float -> Option { a | zoom : Supported } -zoom = - Encode.float >> Option "zoom" - - -{-| The desired bearing, in degrees. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up. --} -bearing : Float -> Option { a | bearing : Supported } -bearing = - Encode.float >> Option "bearing" - - -{-| The desired pitch, in degrees. --} -pitch : Float -> Option { a | pitch : Supported } -pitch = - Encode.float >> Option "pitch" - - -{-| If `zoom` is specified, `around` determines the point around which the zoom is centered. --} -around : LngLat -> Option { a | around : Supported } -around = - encodePair Encode.float >> Option "around" - - -{-| The amount of padding in pixels to add to the given bounds. --} -padding : Padding -> Option { a | padding : Supported } -padding = - encodePadding >> Option "padding" - - -{-| -} -type alias Padding = - { top : Int, right : Int, bottom : Int, left : Int } - - -encodePadding { top, right, bottom, left } = - Encode.object - [ ( "top", Encode.int top ) - , ( "right", Encode.int right ) - , ( "bottom", Encode.int bottom ) - , ( "left", Encode.int left ) - ] - - -{-| If true, the map transitions using `easeTo` . If false, the map transitions using `flyTo`. --} -linear : Bool -> Option { a | linear : Supported } -linear = - Encode.bool >> Option "linear" - - -{-| The maximum zoom level to allow when the map view transitions to the specified bounds. --} -maxZoom : Float -> Option { a | maxZoom : Supported } -maxZoom = - Encode.float >> Option "maxZoom" - - -{-| The zooming "curve" that will occur along the flight path. -A high value maximizes zooming for an exaggerated animation, while a -low value minimizes zooming for an effect closer to `easeTo`. -1.42 is the average value selected by participants in the user study discussed in [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). -A value of `6 ^ 0.25` would be equivalent to the root mean squared average velocity. A value of 1 would produce a circular motion. --} -curve : Float -> Option { a | curve : Supported } -curve = - Encode.float >> Option "curve" - - -{-| The zero-based zoom level at the peak of the flight path. -If `curve` is specified, this option is ignored. --} -minZoom : Float -> Option { a | minZoom : Supported } -minZoom = - Encode.float >> Option "minZoom" - - -{-| The average speed of the animation defined in relation to `curve`. A speed of 1.2 means that the map appears to move along the flight path by 1.2 times `curve` screenfuls every second. A screenful is the map's visible span. It does not correspond to a fixed physical distance, but varies by zoom level. --} -speed : Float -> Option { a | speed : Supported } -speed = - Encode.float >> Option "speed" - - -{-| The average speed of the animation measured in screenfuls per second, assuming a linear timing curve. If `speed` is specified, this option is ignored. --} -screenSpeed : Float -> Option { a | screenSpeed : Supported } -screenSpeed = - Encode.float >> Option "screenSpeed" - - -{-| The animation's maximum duration, measured in milliseconds. If duration exceeds maximum duration, it resets to 0. --} -maxDuration : Float -> Option { a | maxDuration : Supported } -maxDuration = - Encode.float >> Option "maxDuration" - - -encodePair encoder ( a, b ) = - Encode.list [ encoder a, encoder b ] - - -decodePair decoder = - Decode.list decoder - |> Decode.andThen - (\l -> - case l of - [ a, b ] -> - Decode.succeed ( a, b ) - - _ -> - Decode.fail "Doesn't apear to be a pair" - ) - - -makeCmd : Outgoing msg -> Id -> String -> List ( String, Value ) -> Cmd msg -makeCmd prt id command params = - prt <| - Encode.object - (( "command", Encode.string command ) - :: ( "target", Encode.string id ) - :: params - ) - - -{-| Resizes the map according to the dimensions of its container element. - -This command must be sent after the map's container is resized, or when the map is shown after being initially hidden with CSS. - --} -resize : Outgoing msg -> Id -> Cmd msg -resize prt id = - makeCmd prt id "resize" [] - - -{-| Pans and zooms the map to contain its visible area within the specified geographical bounds. This function will also reset the map's bearing to 0 if bearing is nonzero. --} -fitBounds : - Outgoing msg - -> Id - -> - List - (Option - { padding : Supported - , easing : Supported - , linear : Supported - , offset : Supported - , maxZoom : Supported - } - ) - -> ( LngLat, LngLat ) - -> Cmd msg -fitBounds prt id options bounds = - makeCmd prt - id - "fitBounds" - [ ( "bounds", encodePair (encodePair Encode.float) bounds ) - , encodeOptions options - ] - - -{-| Options use phantom types to show which commands support them. --} -type Option support - = Option String Value - - -{-| -} -type Supported - = Supported - - -encodeOptions opts = - ( "options", Encode.object <| List.map (\(Option key val) -> ( key, val )) opts ) - - -{-| Pans the map by the specified offest. --} -panBy : - Outgoing msg - -> Id - -> - List - (Option - { duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - } - ) - -> ( Int, Int ) - -> Cmd msg -panBy prt id options offset = - makeCmd prt id "panBy" [ ( "offset", encodePair Encode.int offset ), encodeOptions options ] - - -{-| Pans the map to the specified location, with an animated transition. --} -panTo : - Outgoing msg - -> Id - -> - List - (Option - { duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - } - ) - -> LngLat - -> Cmd msg -panTo prt id options location = - makeCmd prt id "panTo" [ ( "location", encodePair Encode.float location ), encodeOptions options ] - - -{-| Zooms the map to the specified zoom level, with an animated transition. --} -zoomTo : - Outgoing msg - -> Id - -> - List - (Option - { duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - } - ) - -> Float - -> Cmd msg -zoomTo prt id options zm = - makeCmd prt id "zoomTo" [ ( "zoom", Encode.float zm ), encodeOptions options ] - - -{-| Increases the map's zoom level by 1. --} -zoomIn : - Outgoing msg - -> Id - -> - List - (Option - { duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - } - ) - -> Cmd msg -zoomIn prt id options = - makeCmd prt id "zoomIn" [ encodeOptions options ] - - -{-| Decreases the map's zoom level by 1. --} -zoomOut : - Outgoing msg - -> Id - -> - List - (Option - { duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - } - ) - -> Cmd msg -zoomOut prt id options = - makeCmd prt id "zoomOut" [ encodeOptions options ] - - -{-| Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up. --} -rotateTo : - Outgoing msg - -> Id - -> - List - (Option - { duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - } - ) - -> Float - -> Cmd msg -rotateTo prt id options zm = - makeCmd prt id "rotateTo" [ ( "bearing", Encode.float zm ), encodeOptions options ] - - -{-| Changes any combination of center, zoom, bearing, and pitch, without an animated transition. The map will retain its current values for any details not specified in options. --} -jumpTo : - Outgoing msg - -> Id - -> - List - (Option - { center : Supported - , zoom : Supported - , bearing : Supported - , pitch : Supported - , around : Supported - } - ) - -> Cmd msg -jumpTo prt id options = - makeCmd prt id "jumpTo" [ encodeOptions options ] - - -{-| Changes any combination of center, zoom, bearing, and pitch, with an animated transition between old and new values. The map will retain its current values for any details not specified in options. --} -easeTo : - Outgoing msg - -> Id - -> - List - (Option - { center : Supported - , zoom : Supported - , bearing : Supported - , pitch : Supported - , around : Supported - , duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - } - ) - -> Cmd msg -easeTo prt id options = - makeCmd prt id "easeTo" [ encodeOptions options ] - - -{-| Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that evokes flight. The animation seamlessly incorporates zooming and panning to help the user maintain her bearings even after traversing a great distance. --} -flyTo : - Outgoing msg - -> Id - -> - List - (Option - { center : Supported - , zoom : Supported - , bearing : Supported - , pitch : Supported - , around : Supported - , duration : Supported - , easing : Supported - , offset : Supported - , animate : Supported - , curve : Supported - , minZoom : Supported - , speed : Supported - , screenSpeed : Supported - , maxDuration : Supported - } - ) - -> Cmd msg -flyTo prt id options = - makeCmd prt id "flyTo" [ encodeOptions options ] - - -{-| Stops any animated transition underway. --} -stop : Outgoing msg -> Id -> Cmd msg -stop prt id = - makeCmd prt id "stop" [] - - -{-| Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text). Necessary for supporting languages like Arabic and Hebrew that are written right-to-left. Takes a URL pointing to the Mapbox RTL text plugin source. --} -setRTLTextPlugin : Outgoing msg -> Id -> String -> Cmd msg -setRTLTextPlugin prt id url = - makeCmd prt id "setRTLTextPlugin" [ ( "url", Encode.string url ) ] - - - --- incoming - - -{-| Responds with the map's geographical bounds. Takes a numerical ID that allows you to associate the question with the answer. --} -getBounds : Outgoing msg -> Id -> Int -> Cmd msg -getBounds prt id reqId = - makeCmd prt id "getBounds" [ ( "requestId", Encode.int reqId ) ] - - -{-| The geometry of the query region. Either a point, a bounding box (specified in terms of southwest and northeast points), or what is currently visible in the viewport. --} -type Query - = Viewport - | Point LngLat - | Box LngLat LngLat - - -encodeQuery query = - case query of - Viewport -> - Encode.string "viewport" - - Point lngLat -> - encodePair Encode.float lngLat - - Box sw ne -> - encodePair (encodePair Encode.float) ( sw, ne ) - - -{-| Returns an array of GeoJSON Feature objects representing visible features that satisfy the query parameters. Takes a numerical ID that allows you to associate the question with the answer. - -The response: The properties value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only string and numeric property values are supported (i.e. null, Array, and Object values are not supported). - -Each feature includes a top-level layer property whose value is an object representing the style layer to which the feature belongs. Layout and paint properties in this object contain values which are fully evaluated for the given zoom level and feature. - -Features from layers whose visibility property is "none", or from layers whose zoom range excludes the current zoom level are not included. Symbol features that have been hidden due to text or icon collision are not included. Features from all other layers are included, including features that may have no visible contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to 0. - -The topmost rendered feature appears first in the returned array, and subsequent features are sorted by descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low zoom levels) are returned only once (though subject to the following caveat). - -Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering. - --} -queryRenderedFeatures : Outgoing msg -> Id -> Int -> List (Option { layers : Supported, filter : Supported }) -> Query -> Cmd msg -queryRenderedFeatures prt id reqId options query = - makeCmd prt - id - "queryRenderedFeatures" - [ ( "requestId", Encode.int reqId ) - , ( "query", encodeQuery query ) - , encodeOptions options - ] - - -{-| A list of style layer IDs for the query to inspect. Only features within these layers will be returned. If this parameter is not set, all layers will be checked. --} -layers : List String -> Option { a | layers : Supported } -layers = - List.map Encode.string >> Encode.list >> Option "layers" - - -{-| A filter to limit query results. --} -filter : Expression DataExpression Bool -> Option { a | filter : Supported } -filter = - Mapbox.Expression.encode >> Option "filter" - - -{-| A response to the queries. See the relevant methods for more information. --} -type Response - = GetBounds Int ( LngLat, LngLat ) - | QueryRenderedFeatures Int (List Value) - | Error String - - -{-| Wraps an incoming port so that you can get nicer subscritions: - - port elmMapboxIncoming : (Value -> msg) -> Sub msg - - - -- exposed - - queryResults : (Response -> msg) -> Sub msg - - queryResuls = - Mapbox.Cmd.queryResults elmMapboxIncoming - --} -queryResults : ((Value -> msg) -> Sub msg) -> (Response -> msg) -> Sub msg -queryResults prt tagger = - prt (decodeResponse >> tagger) - - -responseDecoder = - Decode.field "type" Decode.string - |> Decode.andThen - (\s -> - case s of - "getBounds" -> - Decode.map2 GetBounds (Decode.field "id" Decode.int) (Decode.field "bounds" (decodePair (decodePair Decode.float))) - - "queryRenderedFeatures" -> - Decode.map2 QueryRenderedFeatures (Decode.field "id" Decode.int) (Decode.field "features" (Decode.list Decode.value)) - - _ -> - Decode.fail <| "Unrecognized response type: " ++ s - ) - - -decodeResponse value = - case Decode.decodeValue responseDecoder value of - Ok res -> - res - - Err e -> - Error e diff --git a/src/Mapbox/Cmd/Internal.elm b/src/Mapbox/Cmd/Internal.elm new file mode 100644 index 0000000..1445e78 --- /dev/null +++ b/src/Mapbox/Cmd/Internal.elm @@ -0,0 +1,14 @@ +module Mapbox.Cmd.Internal exposing (..) + +import Json.Encode as Encode exposing (Value) + + +{-| Options use phantom types to show which commands support them. +-} +type Option support + = Option String Value + + +{-| -} +type Supported + = Supported diff --git a/src/Mapbox/Cmd/Option.elm b/src/Mapbox/Cmd/Option.elm new file mode 100644 index 0000000..6157de4 --- /dev/null +++ b/src/Mapbox/Cmd/Option.elm @@ -0,0 +1,188 @@ +module Mapbox.Cmd.Option exposing (..) + +{-| + + +### Animation options + +Options common to map movement commands that involve animation, such as panBy and easeTo, controlling the duration and easing function of the animation. All properties are optional. + +@docs duration, easing, offset, animate + +@docs curve, minZoom, speed, screenSpeed, maxDuration + + +### Camera Options + +Options common to `jumpTo`, `easeTo`, and `flyTo`, controlling the desired location, zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current camera value for that property will remain unchanged. + +@docs center, zoom, bearing, pitch, around + + +### Fiting bounds + +@docs padding, Padding, linear, maxZoom + +@docs layers, filter + +-} + +import Mapbox.Helpers exposing (encodePair) +import Json.Encode as Encode exposing (Value) +import Mapbox.Cmd.Internal as Internal exposing (Option(..), Supported) +import Mapbox.Helpers exposing (encodePair) +import LngLat exposing (LngLat) +import Mapbox.Expression exposing (DataExpression, Expression) + + +{-| The animation's duration, measured in milliseconds. +-} +duration : Int -> Option { a | duration : Supported } +duration = + Encode.int >> Option "duration" + + +{-| The name of an easing function. These must be passed to `elmMapbox` +in the `easingFunctions` option. +-} +easing : String -> Option { a | easing : Supported } +easing = + Encode.string >> Option "easing" + + +{-| Offset of the target center relative to real map container center at the end of animation. +-} +offset : ( Int, Int ) -> Option { a | offset : Supported } +offset = + encodePair Encode.int >> Option "offset" + + +{-| If false, no animation will occur. +-} +animate : Bool -> Option { a | animate : Supported } +animate = + Encode.bool >> Option "animate" + + +{-| The desired center. +-} +center : LngLat -> Option { a | center : Supported } +center = + LngLat.encodeAsPair >> Option "center" + + +{-| The desired zoom level. +-} +zoom : Float -> Option { a | zoom : Supported } +zoom = + Encode.float >> Option "zoom" + + +{-| The desired bearing, in degrees. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up. +-} +bearing : Float -> Option { a | bearing : Supported } +bearing = + Encode.float >> Option "bearing" + + +{-| The desired pitch, in degrees. +-} +pitch : Float -> Option { a | pitch : Supported } +pitch = + Encode.float >> Option "pitch" + + +{-| If `zoom` is specified, `around` determines the point around which the zoom is centered. +-} +around : LngLat -> Option { a | around : Supported } +around = + LngLat.encodeAsPair >> Option "around" + + +{-| The amount of padding in pixels to add to the given bounds. +-} +padding : Padding -> Option { a | padding : Supported } +padding = + encodePadding >> Option "padding" + + +{-| -} +type alias Padding = + { top : Int, right : Int, bottom : Int, left : Int } + + +encodePadding { top, right, bottom, left } = + Encode.object + [ ( "top", Encode.int top ) + , ( "right", Encode.int right ) + , ( "bottom", Encode.int bottom ) + , ( "left", Encode.int left ) + ] + + +{-| If true, the map transitions using `easeTo` . If false, the map transitions using `flyTo`. +-} +linear : Bool -> Option { a | linear : Supported } +linear = + Encode.bool >> Option "linear" + + +{-| The maximum zoom level to allow when the map view transitions to the specified bounds. +-} +maxZoom : Float -> Option { a | maxZoom : Supported } +maxZoom = + Encode.float >> Option "maxZoom" + + +{-| The zooming "curve" that will occur along the flight path. +A high value maximizes zooming for an exaggerated animation, while a +low value minimizes zooming for an effect closer to `easeTo`. +1.42 is the average value selected by participants in the user study discussed in [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). +A value of `6 ^ 0.25` would be equivalent to the root mean squared average velocity. A value of 1 would produce a circular motion. +-} +curve : Float -> Option { a | curve : Supported } +curve = + Encode.float >> Option "curve" + + +{-| The zero-based zoom level at the peak of the flight path. +If `curve` is specified, this option is ignored. +-} +minZoom : Float -> Option { a | minZoom : Supported } +minZoom = + Encode.float >> Option "minZoom" + + +{-| The average speed of the animation defined in relation to `curve`. A speed of 1.2 means that the map appears to move along the flight path by 1.2 times `curve` screenfuls every second. A screenful is the map's visible span. It does not correspond to a fixed physical distance, but varies by zoom level. +-} +speed : Float -> Option { a | speed : Supported } +speed = + Encode.float >> Option "speed" + + +{-| The average speed of the animation measured in screenfuls per second, assuming a linear timing curve. If `speed` is specified, this option is ignored. +-} +screenSpeed : Float -> Option { a | screenSpeed : Supported } +screenSpeed = + Encode.float >> Option "screenSpeed" + + +{-| The animation's maximum duration, measured in milliseconds. If duration exceeds maximum duration, it resets to 0. +-} +maxDuration : Float -> Option { a | maxDuration : Supported } +maxDuration = + Encode.float >> Option "maxDuration" + + +{-| A list of style layer IDs for the query to inspect. Only features within these layers will be returned. If this parameter is not set, all layers will be checked. +-} +layers : List String -> Option { a | layers : Supported } +layers = + List.map Encode.string >> Encode.list >> Option "layers" + + +{-| A filter to limit query results. +-} +filter : Expression DataExpression Bool -> Option { a | filter : Supported } +filter = + Mapbox.Expression.encode >> Option "filter" diff --git a/src/Mapbox/Cmd/Template.elm b/src/Mapbox/Cmd/Template.elm new file mode 100644 index 0000000..d0f306e --- /dev/null +++ b/src/Mapbox/Cmd/Template.elm @@ -0,0 +1,435 @@ +module Mapbox.Cmd.Template exposing (Id, Outgoing, Option, Supported, panBy, panTo, zoomTo, zoomIn, zoomOut, rotateTo, jumpTo, easeTo, flyTo, stop, fitBounds, setRTLTextPlugin, Response(..), queryResults, getBounds, queryRenderedFeatures, Query(..), resize) + +{-| This module has a bunch of essentially imperative commands for your map. + +However, since a published library can't have ports in it, you will need to do some setup. The easiest way to do this is to copy [this file into your app](https://github.com/gampleman/elm-mapbox/blob/master/examples/MapCommands.elm). You can see the module docs for that [here](https://github.com/gampleman/elm-mapbox/blob/master/docs/MapCommands.md). + +@docs Id, Outgoing, Option, Supported + +You can of course customize the module you copy into your codebase to support things like having multiple maps on the page at once, etc. + + +### Moving the map around + +@docs panBy, panTo, zoomTo, zoomIn, zoomOut, rotateTo, jumpTo, easeTo, flyTo, stop + + +### Fiting bounds + +@docs fitBounds + + +### Other + +@docs setRTLTextPlugin, resize + + +### Querying the map + +@docs Response, queryResults, getBounds, queryRenderedFeatures, Query + +-} + +import Json.Decode as Decode +import Json.Encode as Encode exposing (Value) +import Mapbox.Cmd.Internal as Internal exposing (Option(..), Supported) +import Mapbox.Helpers exposing (encodePair) +import LngLat exposing (LngLat) + + +{-| The type of a port that you need to provide for this module to work. +-} +type alias Outgoing msg = + Value -> Cmd msg + + +{-| Every command takes the DOM id of the map that it should operate on. +-} +type alias Id = + String + + +type alias Option support = + Internal.Option support + + +type alias Supported = + Internal.Supported + + + +-- AnimationOptions + + +decodePair decoder = + Decode.list decoder + |> Decode.andThen + (\l -> + case l of + [ a, b ] -> + Decode.succeed ( a, b ) + + _ -> + Decode.fail "Doesn't apear to be a pair" + ) + + +makeCmd : Outgoing msg -> Id -> String -> List ( String, Value ) -> Cmd msg +makeCmd prt id command params = + prt <| + Encode.object + (( "command", Encode.string command ) + :: ( "target", Encode.string id ) + :: params + ) + + +{-| Resizes the map according to the dimensions of its container element. + +This command must be sent after the map's container is resized, or when the map is shown after being initially hidden with CSS. + +-} +resize : Outgoing msg -> Id -> Cmd msg +resize prt id = + makeCmd prt id "resize" [] + + +{-| Pans and zooms the map to contain its visible area within the specified geographical bounds. This function will also reset the map's bearing to 0 if bearing is nonzero. +-} +fitBounds : + Outgoing msg + -> Id + -> + List + (Option + { padding : Supported + , easing : Supported + , linear : Supported + , offset : Supported + , maxZoom : Supported + } + ) + -> ( LngLat, LngLat ) + -> Cmd msg +fitBounds prt id options bounds = + makeCmd prt + id + "fitBounds" + [ ( "bounds", encodePair LngLat.encodeAsPair bounds ) + , encodeOptions options + ] + + +encodeOptions opts = + ( "options", Encode.object <| List.map (\(Option key val) -> ( key, val )) opts ) + + +{-| Pans the map by the specified offest. +-} +panBy : + Outgoing msg + -> Id + -> + List + (Option + { duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + } + ) + -> ( Int, Int ) + -> Cmd msg +panBy prt id options offset = + makeCmd prt id "panBy" [ ( "offset", encodePair Encode.int offset ), encodeOptions options ] + + +{-| Pans the map to the specified location, with an animated transition. +-} +panTo : + Outgoing msg + -> Id + -> + List + (Option + { duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + } + ) + -> LngLat + -> Cmd msg +panTo prt id options location = + makeCmd prt id "panTo" [ ( "location", LngLat.encodeAsPair location ), encodeOptions options ] + + +{-| Zooms the map to the specified zoom level, with an animated transition. +-} +zoomTo : + Outgoing msg + -> Id + -> + List + (Option + { duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + } + ) + -> Float + -> Cmd msg +zoomTo prt id options zm = + makeCmd prt id "zoomTo" [ ( "zoom", Encode.float zm ), encodeOptions options ] + + +{-| Increases the map's zoom level by 1. +-} +zoomIn : + Outgoing msg + -> Id + -> + List + (Option + { duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + } + ) + -> Cmd msg +zoomIn prt id options = + makeCmd prt id "zoomIn" [ encodeOptions options ] + + +{-| Decreases the map's zoom level by 1. +-} +zoomOut : + Outgoing msg + -> Id + -> + List + (Option + { duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + } + ) + -> Cmd msg +zoomOut prt id options = + makeCmd prt id "zoomOut" [ encodeOptions options ] + + +{-| Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up. +-} +rotateTo : + Outgoing msg + -> Id + -> + List + (Option + { duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + } + ) + -> Float + -> Cmd msg +rotateTo prt id options zm = + makeCmd prt id "rotateTo" [ ( "bearing", Encode.float zm ), encodeOptions options ] + + +{-| Changes any combination of center, zoom, bearing, and pitch, without an animated transition. The map will retain its current values for any details not specified in options. +-} +jumpTo : + Outgoing msg + -> Id + -> + List + (Option + { center : Supported + , zoom : Supported + , bearing : Supported + , pitch : Supported + , around : Supported + } + ) + -> Cmd msg +jumpTo prt id options = + makeCmd prt id "jumpTo" [ encodeOptions options ] + + +{-| Changes any combination of center, zoom, bearing, and pitch, with an animated transition between old and new values. The map will retain its current values for any details not specified in options. +-} +easeTo : + Outgoing msg + -> Id + -> + List + (Option + { center : Supported + , zoom : Supported + , bearing : Supported + , pitch : Supported + , around : Supported + , duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + } + ) + -> Cmd msg +easeTo prt id options = + makeCmd prt id "easeTo" [ encodeOptions options ] + + +{-| Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that evokes flight. The animation seamlessly incorporates zooming and panning to help the user maintain her bearings even after traversing a great distance. +-} +flyTo : + Outgoing msg + -> Id + -> + List + (Option + { center : Supported + , zoom : Supported + , bearing : Supported + , pitch : Supported + , around : Supported + , duration : Supported + , easing : Supported + , offset : Supported + , animate : Supported + , curve : Supported + , minZoom : Supported + , speed : Supported + , screenSpeed : Supported + , maxDuration : Supported + } + ) + -> Cmd msg +flyTo prt id options = + makeCmd prt id "flyTo" [ encodeOptions options ] + + +{-| Stops any animated transition underway. +-} +stop : Outgoing msg -> Id -> Cmd msg +stop prt id = + makeCmd prt id "stop" [] + + +{-| Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text). Necessary for supporting languages like Arabic and Hebrew that are written right-to-left. Takes a URL pointing to the Mapbox RTL text plugin source. +-} +setRTLTextPlugin : Outgoing msg -> Id -> String -> Cmd msg +setRTLTextPlugin prt id url = + makeCmd prt id "setRTLTextPlugin" [ ( "url", Encode.string url ) ] + + + +-- incoming + + +{-| Responds with the map's geographical bounds. Takes a numerical ID that allows you to associate the question with the answer. +-} +getBounds : Outgoing msg -> Id -> Int -> Cmd msg +getBounds prt id reqId = + makeCmd prt id "getBounds" [ ( "requestId", Encode.int reqId ) ] + + +{-| The geometry of the query region. Either a point, a bounding box (specified in terms of southwest and northeast points), or what is currently visible in the viewport. +-} +type Query + = Viewport + | Point LngLat + | Box LngLat LngLat + + +encodeQuery query = + case query of + Viewport -> + Encode.string "viewport" + + Point lngLat -> + LngLat.encodeAsPair lngLat + + Box sw ne -> + encodePair LngLat.encodeAsPair ( sw, ne ) + + +{-| Returns an array of GeoJSON Feature objects representing visible features that satisfy the query parameters. Takes a numerical ID that allows you to associate the question with the answer. + +The response: The properties value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only string and numeric property values are supported (i.e. null, Array, and Object values are not supported). + +Each feature includes a top-level layer property whose value is an object representing the style layer to which the feature belongs. Layout and paint properties in this object contain values which are fully evaluated for the given zoom level and feature. + +Features from layers whose visibility property is "none", or from layers whose zoom range excludes the current zoom level are not included. Symbol features that have been hidden due to text or icon collision are not included. Features from all other layers are included, including features that may have no visible contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to 0. + +The topmost rendered feature appears first in the returned array, and subsequent features are sorted by descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low zoom levels) are returned only once (though subject to the following caveat). + +Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering. + +-} +queryRenderedFeatures : Outgoing msg -> Id -> Int -> List (Option { layers : Supported, filter : Supported }) -> Query -> Cmd msg +queryRenderedFeatures prt id reqId options query = + makeCmd prt + id + "queryRenderedFeatures" + [ ( "requestId", Encode.int reqId ) + , ( "query", encodeQuery query ) + , encodeOptions options + ] + + +{-| A response to the queries. See the relevant methods for more information. +-} +type Response + = GetBounds Int ( LngLat, LngLat ) + | QueryRenderedFeatures Int (List Value) + | Error String + + +{-| Wraps an incoming port so that you can get nicer subscritions: + + port elmMapboxIncoming : (Value -> msg) -> Sub msg + + + -- exposed + + queryResults : (Response -> msg) -> Sub msg + + queryResuls = + Mapbox.Cmd.queryResults elmMapboxIncoming + +-} +queryResults : ((Value -> msg) -> Sub msg) -> (Response -> msg) -> Sub msg +queryResults prt tagger = + prt (decodeResponse >> tagger) + + +responseDecoder = + Decode.field "type" Decode.string + |> Decode.andThen + (\s -> + case s of + "getBounds" -> + Decode.map2 GetBounds (Decode.field "id" Decode.int) (Decode.field "bounds" (decodePair LngLat.decodeFromPair)) + + "queryRenderedFeatures" -> + Decode.map2 QueryRenderedFeatures (Decode.field "id" Decode.int) (Decode.field "features" (Decode.list Decode.value)) + + _ -> + Decode.fail <| "Unrecognized response type: " ++ s + ) + + +decodeResponse value = + case Decode.decodeValue responseDecoder value of + Ok res -> + res + + Err e -> + Error e diff --git a/src/Mapbox/Element.elm b/src/Mapbox/Element.elm index 13f5f00..83f818e 100644 --- a/src/Mapbox/Element.elm +++ b/src/Mapbox/Element.elm @@ -1,4 +1,4 @@ -module Mapbox.Element exposing (map, css, MapboxAttr, token, id, maxZoom, minZoom, maxBounds, LngLat, renderWorldCopies, featureState, EventData, TouchEvent, eventFeaturesFilter, eventFeaturesLayers, onMouseDown, onMouseUp, onMouseOver, onMouseMove, onClick, onDblClick, onMouseOut, onContextMenu, onZoom, onZoomStart, onZoomEnd, onRotate, onRotateStart, onRotateEnd, onTouchEnd, onTouchMove, onTouchCancel, controlledMap, Viewport) +module Mapbox.Element exposing (map, css, MapboxAttr, token, id, maxZoom, minZoom, maxBounds, renderWorldCopies, EventData, TouchEvent, eventFeaturesFilter, eventFeaturesLayers, onMouseDown, onMouseUp, onMouseOver, onMouseMove, onClick, onDblClick, onMouseOut, onContextMenu, onZoom, onZoomStart, onZoomEnd, onRotate, onRotateStart, onRotateEnd, onTouchEnd, onTouchMove, onTouchCancel) {-| This library wraps a Custom Element that actually renders a map. @@ -7,7 +7,7 @@ module Mapbox.Element exposing (map, css, MapboxAttr, token, id, maxZoom, minZoo ### Attributes -@docs token, id, maxZoom, minZoom, maxBounds, LngLat, renderWorldCopies, featureState +@docs token, id, maxZoom, minZoom, maxBounds, renderWorldCopies ### Events @@ -16,11 +16,6 @@ module Mapbox.Element exposing (map, css, MapboxAttr, token, id, maxZoom, minZoo @docs onMouseDown, onMouseUp, onMouseOver, onMouseMove, onClick, onDblClick, onMouseOut, onContextMenu, onZoom, onZoomStart, onZoomEnd, onRotate, onRotateStart, onRotateEnd, onTouchEnd, onTouchMove, onTouchCancel - -### Controlled mode - -@docs controlledMap, Viewport - -} import Html exposing (Attribute, Html, node) @@ -28,8 +23,10 @@ import Html.Attributes exposing (attribute, property) import Html.Events exposing (Options) import Json.Decode as Decode exposing (Decoder, Value) import Json.Encode as Encode +import LngLat exposing (LngLat) import Mapbox.Expression exposing (DataExpression, Expression) import Mapbox.Style exposing (Style) +import Mapbox.Helpers exposing (encodePair) {-| This is the type that all attributes have. @@ -99,17 +96,11 @@ id = attribute "id" >> MapboxAttr -{-| A longitude latitude pair (in that order). --} -type alias LngLat = - ( Float, Float ) - - {-| If set, the map will be constrained to the given bounds. The bounds are the `(south-west corner, north-east corner)`. -} maxBounds : ( LngLat, LngLat ) -> MapboxAttr msg maxBounds = - encodePair (encodePair Encode.float) >> property "maxBounds" >> MapboxAttr + encodePair LngLat.encodeAsPair >> property "maxBounds" >> MapboxAttr {-| If true, multiple copies of the world will be rendered, when zoomed out. @@ -119,23 +110,6 @@ renderWorldCopies = Encode.bool >> property "renderWorldCopies" >> MapboxAttr -encodePair encoder ( a, b ) = - Encode.list [ encoder a, encoder b ] - - -decodePair decoder = - Decode.list decoder - |> Decode.andThen - (\l -> - case l of - [ a, b ] -> - Decode.succeed ( a, b ) - - _ -> - Decode.fail "Doesn't apear to be a pair" - ) - - {-| This is a declarative API for controlling states on the features. The API takes a bunch of GeoJSON features (these can be returned from the event listeners for example). They should at a minimum have these properties defined: @@ -146,6 +120,8 @@ The API takes a bunch of GeoJSON features (these can be returned from the event Then you can give it a `List ( String, Value )` state. You can use this state infromation through the `Mapbox.Expression.featureState` expression. +This needs more design before release. + -} featureState : List ( Value, List ( String, Value ) ) -> MapboxAttr msg featureState = @@ -220,10 +196,6 @@ type alias TouchEvent = } -decodeLngLat = - Decode.map2 (,) (Decode.field "lng" Decode.float) (Decode.field "lat" Decode.float) - - decodePoint = Decode.map2 (,) (Decode.field "x" Decode.int) (Decode.field "y" Decode.int) @@ -231,7 +203,7 @@ decodePoint = decodeEventData = Decode.map3 EventData (Decode.field "point" decodePoint) - (Decode.field "lngLat" decodeLngLat) + (Decode.field "lngLat" LngLat.decodeFromObject) (Decode.field "features" (Decode.list Decode.value)) @@ -239,7 +211,7 @@ decodeTouchEvent = Decode.map2 TouchEvent (Decode.map3 (List.map3 EventData) (Decode.field "points" (Decode.list decodePoint)) - (Decode.field "lngLats" (Decode.list decodeLngLat)) + (Decode.field "lngLats" (Decode.list LngLat.decodeFromObject)) (Decode.field "perPointFeatures" (Decode.list (Decode.list Decode.value))) ) decodeEventData @@ -408,6 +380,9 @@ type alias Viewport = {-| By default the map is "uncontrolled". By this we mean that it has its own internal state (namely the center, zoom level, pitch and bearing). This is nice if you don't care about these, but it does break some of the niceness of TEA. It also means some advanced interaction techniques are impossible to implement. For this reason we allow controlled mode where no event handlers are attached, but you need to feed the element its state. So it's up to you to implement all the user interactions. In the future, this library may help with that, but in the present this is not available. + +Not done, so let's not release this. + -} controlledMap : Viewport -> List (MapboxAttr msg) -> Style -> Html msg controlledMap { center, zoom, bearing, pitch } attrs style = @@ -415,7 +390,7 @@ controlledMap { center, zoom, bearing, pitch } attrs style = props = property "mapboxStyle" (Mapbox.Style.encode style) :: property "interactive" (Encode.bool False) - :: property "center" (encodePair Encode.float center) + :: property "center" (LngLat.encodeAsPair center) :: property "zoom" (Encode.float zoom) :: property "bearing" (Encode.float bearing) :: property "pitch" (Encode.float pitch) diff --git a/src/Mapbox/Helpers.elm b/src/Mapbox/Helpers.elm index f2072aa..ed66d37 100644 --- a/src/Mapbox/Helpers.elm +++ b/src/Mapbox/Helpers.elm @@ -12,3 +12,7 @@ encodeAnchor v = Map -> Encode.string "map" + + +encodePair encoder ( a, b ) = + Encode.list [ encoder a, encoder b ] diff --git a/src/Mapbox/Source.elm b/src/Mapbox/Source.elm index a927621..7677df8 100644 --- a/src/Mapbox/Source.elm +++ b/src/Mapbox/Source.elm @@ -49,6 +49,7 @@ Tiled sources can also take the following attributes: -} import Json.Encode exposing (Value) +import LngLat exposing (LngLat) {-| Every layer is identified by an id. @@ -115,11 +116,11 @@ getId (Source k _) = k -{-| The longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `sw.lng, sw.lat, ne.lng, ne.lat`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL. +{-| The longitude and latitude of the southwest and northeast corners of the source's bounding box. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL. -} -bounds : Float -> Float -> Float -> Float -> SourceOption any -bounds a b c d = - SourceOption "bounds" (Json.Encode.list [ Json.Encode.float a, Json.Encode.float b, Json.Encode.float c, Json.Encode.float d ]) +bounds : LngLat -> LngLat -> SourceOption any +bounds sw ne = + SourceOption "bounds" (Json.Encode.list [ Json.Encode.float sw.lng, Json.Encode.float sw.lat, Json.Encode.float sw.lng, Json.Encode.float sw.lat ]) {-| Minimum zoom level for which tiles are available, as in the TileJSON spec. @@ -296,20 +297,21 @@ geoJSONFromValue id options data = {-| `(longitude, latitude)` pairs for the corners. You can use the type alias constructor in clockwise order: top left, top right, bottom right, bottom left. -} type alias Coords = - { topLeft : ( Float, Float ) - , topRight : ( Float, Float ) - , bottomRight : ( Float, Float ) - , bottomLeft : ( Float, Float ) + { topLeft : LngLat + , topRight : LngLat + , bottomRight : LngLat + , bottomLeft : LngLat } encodeCoordinates : Coords -> Value encodeCoordinates { topLeft, topRight, bottomRight, bottomLeft } = - let - encodePair ( x, y ) = - Json.Encode.list [ Json.Encode.float x, Json.Encode.float y ] - in - Json.Encode.list [ encodePair topLeft, encodePair topRight, encodePair bottomRight, encodePair bottomLeft ] + Json.Encode.list + [ LngLat.encodeAsPair topLeft + , LngLat.encodeAsPair topRight + , LngLat.encodeAsPair bottomRight + , LngLat.encodeAsPair bottomLeft + ] {-| An image source diff --git a/src/Mapbox/Style.elm b/src/Mapbox/Style.elm index c647814..1793067 100644 --- a/src/Mapbox/Style.elm +++ b/src/Mapbox/Style.elm @@ -30,6 +30,7 @@ You can also use one of these predefined styles. import Array exposing (Array) import Json.Encode as Encode exposing (Value) +import LngLat exposing (LngLat) import Mapbox.Expression exposing (Anchor(Viewport), CameraExpression, Color, Expression, float, floats, rgba) import Mapbox.Helpers exposing (encodeAnchor) import Mapbox.Layer exposing (Layer) @@ -161,9 +162,9 @@ name = {-| Default map center in longitude and latitude. The style center will be used only if the map has not been positioned by other means (e.g. map options or user interaction). -} -defaultCenter : Float -> Float -> MiscAttr -defaultCenter lat lng = - Encode.list [ Encode.float lat, Encode.float lng ] |> MiscAttr "center" +defaultCenter : LngLat -> MiscAttr +defaultCenter = + LngLat.encodeAsPair >> MiscAttr "center" {-| Default zoom level. The style zoom will be used only if the map has not been positioned by other means (e.g. map options or user interaction). -- cgit v1.2.3