Concatenated JS, causes "uncaught promise" error in Google Maps - javascript

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"}

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!

You could run this command below your codes.
google.maps.event.addDomListener(window, 'load', initMap);
I hope this is helpful for you.

Related

Google Maps JavaScript API Callback Error [duplicate]

How to fix the following console errors.
Loading the Google Maps JavaScript API without a callback is not supported
InvalidValueError: not an instance of HTMLInputElement
Because of the above errors, my jobs are not showing in Google search results.
I'm not a developer, so I need suggestions to fix this problem. I will incorporate the necessary changes in my WordPress website.
TL;DR
Use Function.prototype as a noop callback to quickly get rid of the error message.
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=Function.prototype
Full Explanation
According to the Google Maps API documentation, the callback parameter has been required for a very long time. In practice, however, Google has only recently (within the past few days) begun enforcing this requirement.
While it doesn't seem to break anything, it now shows an ugly error message in the console...
Loading the Google Maps JavaScript API without a callback is not supported.
How can I fix it?
The short answer is to specify a callback value. Set the name of the JavaScript function that you would like to trigger once the external API library has finished loading.
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=FUNCTION_NAME
Be warned, you must specify a real function name! Otherwise you'll trigger an "is not a function" error message, and simply be trading one error message for another.
But I don't have/need a callback function!
If you don't actually have a callback function to run immediately after the library loads, you can use Function.prototype as a noop stand-in.
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=Function.prototype
The Function.prototype method is native to JavaScript, and does absolutely nothing... It's exactly what you need in a situation like this!
For more information about Function.prototype, see this unrelated SO thread...
I actually created a noop function so I could keep track of when it was called.
function gmNoop() { console.log('GMap Callback') }
Then added it to my Google map API resource request.
https://maps.googleapis.com/maps/api/js?key='.GOOGLEMAPSKEY.'&callback=gmNoop
The reason I needed this was because my application calls initMap() after other prerequisites. Calling initMap() prior to these other resources would load a map without markers.
I just found this yt video which may help you:
https://www.youtube.com/watch?v=1asukrHEqMM&ab_channel=KnowledgeBase
It didn't help me much as my problem is slightly different, but gave me an idea of what way to go. Hopefully it helps you. Good luck
::::::::::E D I T::::::::::
Basically what you have to do to get rid of this error is to declare the function (aka initMap) before running the script where you make the API call.
The initMap function is the function where the google map is created and given the characteristics and all that.
initMap function looks like this:
function initMap(): void {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
}
The API call is the script line where we put the API-KEY.
<script defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API-KEY&libraries=places&callback=initMap"></script>
I found two ways to do it, the first way is: have a module that you only have to call before the API with a src script.
Example:
<html>
<head>
<script defer src="js/scripts.js" type="module"></script>
<script src="js/module/google.js"></script>
<script defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API-KEY&libraries=places&callback=initMap"></script>
</head>
<body></body>
</html>
Dentro de google.js es donde guardo mi funcion de initMap()
The second way is: write all the code inside a script tag before making the API call.
Example:
<html>
<head>
<script defer src="js/scripts.js" type="module"></script>
<script>
function initMap(): void {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
}
</script>
<script defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API-KEY&libraries=places&callback=initMap"></script>
</head>
<body></body>
</html>
Note that I use defer so that the code loads at the bottom of the
page, this is just my style because I like to declare everything in the
head element.

Ionic 6 - localization of Google Maps API

I am using Angular 13 and Ionic 6 to add Google Maps API V3. Here is a simple example provided by Google to add the map using TypeScript.
When using Ionic, I am supposed to add the following in the index.html file:
<script src="https://maps.googleapis.com/maps/api/js?key=ZZZZZ&language=en&region=ca" async defer>
</script>
Then, I will use it in the appropriate components throughout the application. As you can see, the language and region have been hardcoded in the script. I am not sure how would I allow the user to dynamically choose the language and region.
The objective is to have Google's localization example implemented using Ionic. The languages I am interested in adding are English and French.
I tried to add the script in the html file of the component but that didn't work. I even tried to dynamically remove and insert a script but it seemed too complicated. Any help would be appreciated and thank you in advance!
You can use loader to add google maps dynamically, like mentioned here:
https://developers.google.com/maps/documentation/javascript/overview#js_api_loader_package
const loader = new Loader({
apiKey: "YOUR_API_KEY",
version: "weekly",
...additionalOptions,
});
loader.load().then(() => {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
});
and use variable for language and region selection

Uncaught ReferenceError: require is not defined in Polymer 3.0

I am new to the Polymer 3.0 library, I am trying to implement ArcGIS in Polymer 3.0.
<!-- This Part Belongs to the HTML Template -->
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css">
<script src="https://js.arcgis.com/4.15/"></script>
<div id="viewDiv"></div>
// Here I defined the module of GIS
require([
"esri/Map",
"esri/views/MapView"
], function(Map, MapView) {
var map = new Map({
basemap: "topo-vector"
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [-118.71511, 34.09042],
zoom: 11
});
});
I used require field inside ready function and also outside the function but it doesn't work.
Can anyone please review this and provide me the solution/guideline to resolve it?
There are mainly two ways to integrate ArcGIS API for JavaScript into other frameworks, using Webpack or esri-loader (ArcGIS JS Guide - Using Frameworks).
I will go directly with, is the most versatile way to achieve it. There are several examples on how use the API with many popular frameworks/libraries through esri-loader. Though no polymer3 example, it should not be too difficult to do it taking as example the others.

Can't access Google Maps library in script tag from React component

I've been trying to embed a Google Map on my page via React. In my index.html html, I the followng scipr tag in between my tag
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap" async defer></script>
I need to create the initMap callback function. I want this callback function to be inside my Map component.
1) How would I connect this callback such that the maps API knows where to find it?
2) To actually create the map, I do it through the google object.
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
scrollwheel: false,
zoom: 8
});
However, my React component won't compile because it's complaining that the 'google' object doesn't exist -- meaning it's not being exposed to me as it should. Of course when I go to the console, I can access it. It seems like the component either doesn't have access to it (although it should since the objects from script tags become global, right?) or its accessing it before the library is loaded (which I don't know how to fix even though it says "defer" in the script tag).
Any help would be appreciated. My problem is similar to this, but the accepted answer did not work for me.
I also tried this tutorial to no avail...I'm not sure if I'm missing something.
Quick Example
If u want ignore the error, try add global variable in your eslint config
"globals": {
"google": true
}
In my example, I remove the callback argument in script tag, I did it in my component.
Hope this can help.

Google Maps Apiv3 + Load map on page load + a is NULL

First of all: The map is working.
The script is in scripts.js, which is included at the bottom of the site.
The Google maps script is included in the header (<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>).
The problem is I am getting this a is NULL error and I would like to fix it, although the map is working fine.
I have searched Google and Stackoverflow and tried every possible combination of the answers I found, but either the map is not working, or the map is working, but I get this a is NULL error error.
Here is the simple demo script I am using for testing:
function init() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('resultsGmap'),
myOptions);
}
window.onload=init();
I have tried to use jQuery too like this:
$(function() {
init();
});
But than nothing works at all. I have also tried to do it very simple like this:
init();
Which works (the map works) but the a is NULL error error appears again.
The other thing I tried was:
google.maps.event.addDomListener(window, 'load', init);
But than again the map doesn't display and the error appears.
For various reason I cant do it the way it is in the official example # Google:
<body onload="init()">
Anybody got an idea what I am doing wrong?
Regards and have a good day!
EDIT:
I have just tried to reproduce the error on a blank page and there it doesnt appear - so I guess it is something else in my code (p.s. I am loading the site with the map via ajax and call the script with $.getScript).
Sorry that I didnt check that before. I guess the error lies in there somewhere.
One more thing: Do you guys think it would be very, very bad to just ignore the error? Since the map and every feature is working correctly.
I'm suspecting it has to do with the ID you provide. Is there a (for example) DIV with the ID 'resultsGmap'.
It might have also got to do with the uppercase. Try using lowercase only, optionally with underscores (_)

Categories