UNPKG

react-hook-google-maps

Version:
58 lines (52 loc) 2.01 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var react = require('react'); var initialized = []; function useGoogleMapsApi(apiKey) { var _a = react.useState(), googleApi = _a[0], setGoogleApi = _a[1]; react.useEffect(function () { if (window.google) { // if window.google object is already available just use it setGoogleApi(window.google); return; } var src = "https://maps.googleapis.com/maps/api/js?key=" + apiKey; var existingScript = initialized.find(function (el) { return el.src === src; }); var onLoad = function () { setGoogleApi(window.google); }; if (existingScript) { // if script tag was added by other element just check when it is loaded existingScript.addEventListener("load", onLoad); return; } var script = document.createElement("script"); script.src = src; script.async = true; script.defer = true; script.addEventListener("load", onLoad); document.head.appendChild(script); initialized.push(script); return function () { script.removeEventListener("load", onLoad); script.remove(); initialized.splice(initialized.findIndex(function (el) { return el.src === src; }), 1); }; }, [apiKey]); return googleApi; } function useGoogleMaps(apiKey, options) { var google = useGoogleMapsApi(apiKey); var ref = react.useRef(null); var _a = react.useState(), map = _a[0], setMap = _a[1]; react.useEffect(function () { if (!google || !ref) { return; } setMap(new google.maps.Map(ref.current, options)); }, [google, ref]); return { ref: ref, map: map, google: google }; } exports.useGoogleMaps = useGoogleMaps; exports.useGoogleMapsApi = useGoogleMapsApi; //# sourceMappingURL=index.js.map