0

not very proficient at JS, nor do I really understand what promises are. But I will do my best to describe the issue.

On this location page, I have some inline JS to output a Google Map. Pretty straight forward, and works fine until the JS is concatenated by a plugin.

So the weird part is when this error is thrown, the code below isn't output at all. If I remove concatenation it works fine. This may be an issue with the Wordpress plugin (WP Rocket), and not a javascript specific issue. I'm not sure, hoping for any tips.

The Code:

        <script>function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
                center: { lat: 41.559345, lng: -88.133326 },
                zoom: 16
            });
            //setMarkers(map);
          }

            function setMarkers(map) {

            marker = new google.maps.Marker({
                    position: {lat: 41.559345, lng: -88.133326},
                    map: map,
                     title: "Crest Hill",
                    //icon: customMarker
                });

                marker.addListener('click', function() {
                    map.setZoom(16);
                    map.setCenter(marker.getPosition());
                });
        }

        </script>

The Error:

Uncaught (in promise) Mc {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵    at new Mc (https://maps.googleapis.com/m…QpokXsxbUPOzocygFOXXXXX&callback=initMap:123:96"}
Luyen Dao
  • 1
  • 2

2 Answers2

1

As you said, the concatenation is transforming your initMap into something else that is not a function. It seems to be passed as a callback to the GoogleMapsAPI, and when it tries to execute it, you get an error. I would try the following:

1) Extract your inline script into a it's own file, perhaps called mapInitialiser.js.

2) Include the script in your HTML with <script src="pathToYourScript/mapInitialiser.js"></script>

3) Doing step 2 means that you would need to consider the following implications, described here: How to make a callback to Google Maps init in separate files of a web app

4) Exclude that file from concatenation. You can read more on that in this WP-rocket article.

Good luck!

Barzev
  • 402
  • 3
  • 14
  • Sorry for the late reply, thanks for your answer and your suggestion. I will look into it further, for the time being I loaded a static google map which didn't require a callback. – Luyen Dao Mar 14 '19 at 00:23
1

You could run this command below your codes.

google.maps.event.addDomListener(window, 'load', initMap);

I hope this is helpful for you.

ZhaoRachi
  • 49
  • 6