Stephen Agwu
Stephen Agwu

Reputation: 1023

How do I use google maps async callback with knockout and webpack?

Hi all. I'm trying to integrate google maps api with knockout and webpack. I've set my request for the google maps api directly in my html. The script includes a callback function that I want to execute once its finished loading. But when I run the server I get the error "initMap is not a function." I think this is happening because the function is located in a bundle but I'm not sure. Does anybody know why this is happening? Heres the js that I'm bundling:

import ko from 'knockout';


function initMap() {
  console.log('hey')
}


var MyApp = () => {
}


ko.applyBindings(new MyApp())

Heres the html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Neighborhood Map</title>
    <link rel="stylesheet" type="text/css" href="./css/main.css"
  </head>
  <body>
    <div id="map">
    </div>


    <script type="text/javascript" src="build/bundle.js"></script>
    <script defer
      src="http://maps.google.com/maps/api/js?key=[KEY]&v=3&callback=initMap">
    </script>

  </body>
</html>

Here's my webpack config file:

const path = require('path');

module.exports = {
    devtool: 'sourcemap',
      entry: './app.js',
      output: {
        path: path.resolve('build', ''),
        filename: 'bundle.js'
      },
      module: {
      noParse: /node_modules\/knockout\/build\/output\/*.js/,
      loaders: [
        {
          test: /\.html$/, loader: 'html-loader'
        },
          {
            test: /\.js?$/,
            exclude: /(node_modules)/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015']
            }
          },
        ]
    }
};

FYI I've tried putting the initMap funtion in MyApp variable as well as leaving as seen as a global function. Neither option works. Do you think I should request the script within the js file instead as a script in the html? If so, what would be the best way to do this?

Upvotes: 3

Views: 1194

Answers (1)

Stephen Agwu
Stephen Agwu

Reputation: 1023

After days of scouring the internet I finally found the answer here: Calling webpacked code from outside (HTML script tag)

The answer I used is actually the 3rd accepted answer. It involves setting the function as a property of the window and exporting the function

window.initMap = initMap
export function initMap() { function stuff }

Please, if this answer helps you, go to that site and upvote that answer so it becomes the accepted answer.

Upvotes: 2

Related Questions