Google Map component, with reagent and reframe. Questions asked on Clojurians #re-frame's channel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Following code is WRONG, see comments for details. | |
(defn google-map [] | |
(let [pos (subscribe [:current-position])] | |
(reagent/create-class | |
{:reagent-render | |
(fn [] | |
[:div | |
[:h4 "Map"] | |
[:div#map-canvas {:style {:height "400px"}}]]) | |
:component-did-mount | |
(fn [] | |
(let [map-canvas (.getElementById js/document "map-canvas") | |
map-options (clj->js {"zoom" 9}) | |
gmap (js/google.maps.Map. map-canvas map-options) | |
marker (js/google.maps.Marker. (clj->js {:map gmap :title "Drone"}))] | |
(reagent.ratom/run! | |
(let [latlng (js/google.maps.LatLng. (:latitude @pos) (:longitude @pos))] | |
(.setPosition marker latlng) | |
(.panTo gmap latlng)))))}))) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Another attempt, using props and lifecycle to udpate marker position | |
(defn gmap-component [] | |
(let [gmap (atom nil) | |
options (clj->js {"zoom" 9}) | |
update (fn [comp] | |
(let [{:keys [latitude longitude]} (reagent/props comp) | |
latlng (js/google.maps.LatLng. latitude longitude)] | |
(.setPosition (:marker @gmap) latlng) | |
(.panTo (:map @gmap) latlng)))] | |
(reagent/create-class | |
{:reagent-render (fn [] | |
[:div | |
[:h4 "Map"] | |
[:div#map-canvas {:style {:height "400px"}}]]) | |
:component-did-mount (fn [comp] | |
(let [canvas (.getElementById js/document "map-canvas") | |
gm (js/google.maps.Map. canvas options) | |
marker (js/google.maps.Marker. (clj->js {:map gm :title "Drone"}))] | |
(reset! gmap {:map gm :marker marker})) | |
(update comp)) | |
:component-did-update update | |
:display-name "gmap-component"}))) | |
(defn gmap-wrapper [] | |
(let [pos (subscribe [:current-position])] | |
(fn [] | |
[gmap-component @pos]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When using this I have found it important to run :component-will-unmount to dispose of the stateful component