Skip to content Skip to sidebar Skip to footer

Is There A Way To Import The Google Maps Api Into React Without A Script Tag?

I am trying to integrate the Google Maps API into my ReactJS and Cordova project just so I can use the places autocomplete. I do not need to display the whole map. Currently, I am

Solution 1:

You can load it via javascript;

jQuery module -

(function (global) {
    "use strict";

    functiononDeviceReady () {
        document.addEventListener("online", onOnline, false);
        document.addEventListener("resume", onResume, false);
        loadMapsApi();
    }

    functiononOnline () {
        loadMapsApi();
    }

    functiononResume () {
        loadMapsApi();
    }

    functionloadMapsApi () {
        if(navigator.connection.type === Connection.NONE || google.maps) {
            return;
        }
        $.getScript('https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=true&callback=onMapsApiLoaded');
    }

    global.onMapsApiLoaded = function () {
        // Maps API loaded and ready to be used.var map = new google.maps.Map(document.getElementById("map"), {});
    };

    document.addEventListener("deviceready", onDeviceReady, false);

})(window);

loadMapsApi() function -

function loadMapsApi () {
    if (navigator.connection.type === Connection.NONE || (global.google !== undefined && global.google.maps)) {
        return;
    }
    // load maps api
}

This ways best as it handles being offline.

You can read up on it more here.

Solution 2:

there always a lib four you :) this is the first result from google. Enjoy :)

Solution 3:

I've used JavaScript in my map component to load the script tag into the DOM. I know that this solution still ultimately uses a script tag, but I found it to be the most elegant solution.

constloadMapsApi = () => {
    let index = window.document.getElementsByTagName("script")[0];

    let script = window.document.createElement("script");

    script.async = true;
    script.defer = true;
    script.src =
      "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&callback=initMap";

    if (index.parentNode !== null) {
      index.parentNode.insertBefore(script, index);
    }
  };

This approach also requires defining the callback required by the google api link. I put this logic in a useEffect hook that binds the callback to the window object.

constinitMap = () => {
    const map = newwindow.google.maps.Map(document.getElementById("map"), {
      center: mapOptions.center,
      zoom: mapOptions.zoom,
      styles: require('./options.json')
    });
  };

  useEffect(() => {
    window.initMap = initMap;
  }, []);

Post a Comment for "Is There A Way To Import The Google Maps Api Into React Without A Script Tag?"