The system encountered an error due to the absence of a defined Google or a MissingKeyMapError from the

Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial.

<div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}">
    <ng-map class="content-pane" center="41,-87" zoom="5"> 
    ...
    </ng-map>
</div>

While working on my controller, I encountered a common issue like this:

var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < this.positions.length; i++) {
    var latlng = new google.maps.LatLng(this.positions[i][0], this.positions[i][1]);
    bounds.extend(latlng);
}

This led to an error stating 'google is not defined' as shown below:

angular.js:13708 ReferenceError: google is not defined
    at new app.component.controller (map.component.js:13)
    at Object.invoke (angular.js:4709)
    at $controllerInit (angular.js:10234)
    at nodeLinkFn (angular.js:9147)
    at angular.js:9553
    at processQueue (angular.js:16170)
    at angular.js:16186
    at Scope.$eval (angular.js:17444)
    at Scope.$digest (angular.js:17257)
    at Scope.$apply (angular.js:17552)

After some online research, I came across a related bug report in this link. The suggestion was to refer back to the tutorial example I had been using to resolve the issue, as it included script-tags-for-development.js which eagerly loads the required script. However, implementing this solution did not fully resolve the problem.

document.write([
  '<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>',
...

Adding this script to the HTML resolved one issue but introduced another - 'Google Maps API error: MissingKeyMapError'. It became apparent that hardcoding the API key into the HTML head was not the ideal approach for me, as I required configurability within my Angular application.

To address the 'missing API key' error, I followed a helpful tutorial suggesting the use of a lazy-load directive. However, this brought me back to the initial problem I faced.

If you need to pass in an API key to the javascript, you can set a scope variable in your controller (e.g. $scope.googleMapsUrl="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE";). This can be set from a constant value in your app to standardise the API key to pass to google for multiple controllers.

<div map-lazy-load="https://maps.google.com/maps/api/js"
  map-lazy-load-params="">
  <ng-map center="41,-87" zoom="3"></ng-map>
</div>

Therefore, my question remains: How do the official ng-map tutorials/examples function without requiring a Google Maps API key? And how can I successfully overcome the 'google not found' error when utilizing the lazy-load directive instead of hardcoding the API key in the HTML head?

Answer №1

The issue I encountered stemmed from the presence of the async attribute in the script tag:

<script src="https://maps.googleapis.com/maps/api/js?key=xxx" async defer></script>

By removing the async attribute, everything started functioning correctly. It is important to note that by doing so, the script now blocks while loading:

The async attribute allows the browser to render the rest of your website while the Maps JavaScript API loads. Once the API is ready, it executes the specified function using the callback parameter.

For more details, refer to https://developers.google.com/maps/documentation/javascript/tutorial?hl=en#Loading_the_Maps_API

Another suggestion is to utilize ngMap's lazy-loading feature:

<div map-lazy-load="https://maps.google.com/maps/api/js"
     map-lazy-load-params="{{googleMapsUrl}}">
  <ng-map center="41,-87" zoom="3"></ng-map>
</div>

Explore further at https://github.com/allenhwkim/angularjs-google-maps#lazy-loading-of-google-maps-javascript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response. ControlledAutoComplete.jsx import { Autocomplete, TextField } from "@mui/mater ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

javascript display error message in innerHTML if passwords do not match

Hello, I found your code to be helpful but I am facing an issue. I want to display a message using innerHTML when the passwords do not match. I have been trying to implement this feature but it is not working for me. Below is my current code. Please provid ...

Ensure Next.js retains the route when moving from one screen to another

I am currently facing a challenge in Next.js while creating a Dashboard. The root route for this dashboard would be: /dashboard/ Within this route, users can select different stores to access their respective dashboards. When a user clicks on a specific s ...

JavaScript functions flawlessly when run on a local machine, but encounters issues when transferred to a server

My JavaScript code is functioning perfectly on my local machine, but as soon as I upload it to my web server, it stops working. The website in question is www.turnbulldesigns.co.uk if you want to take a look. I have transferred the complete folder structu ...

The webpage is not refreshing or reloading despite using window.location.href

When creating a refreshcart() function, the window.location.href is assigned to currentUrl. However, when making an ajax call in the else block with window.location.href = currentUrl, true; it does not successfully refresh the page. $(document).ready(fu ...

Looking to introduce Vue.js into an established SSR website?

Can Vue be used to create components that can be instantiated onto custom tags rendered by a PHP application, similar to "custom elements light"? While mounting the Vue instance onto the page root element seems to work, it appears that Vue uses the entire ...

Filtering JSON data by date range in React JS

I have a dataset with JSON data containing ISO dates, and my goal is to filter out entries based on the "date_created" field falling within a specific date range. The time component should be ignored in this comparison, and the original JSON data should re ...

Performing a single AJAX call from a JavaScript loop is more efficient than iterating through multiple AJAX calls

I am working with a 2D array in JavaScript. Currently, I have a for loop where I make an AJAX call to update the database. I understand that this approach is not efficient, and I am seeking a way to update the database with just one AJAX call within the ...

Do iframes not utilize parental jquery?

I have a homepage that utilizes jQuery by loading it from the ajax google APIs in the head> tag. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js" type="text/javascript"></script> I attempted to use jQuery functions ...

Exploring JavaScript Object-Oriented Programming (OOP) concepts. Delving into the

Here is a sample of JavaScript OOP that I am currently studying. I'm puzzled about why getA() and getC() are returning undefined, but getB() returns 2 when I update the variable B in the constructor and assign it to b. When I execute getD(), it appea ...

Encountered an issue with reading the property 'drop' from an undefined source during a straightforward migration

I recently started using the migrate-mongo library and encountered an issue during a simple migration process to create a view. Despite success in migrating up, I faced an error when attempting to migrate down. ERROR: Could not migrate down 20220620114132 ...

Is it possible for me to make the default export anonymous?

Why bother naming the export if you already have a file with the default export name? This seems redundant and goes against the DRY principle. While there is a rule that discourages anonymous default exports, how can we enforce an error when someone does ...

elements that are left between two URLs

I recently started learning Angular and I'm working on creating a website where certain elements persist between different URLs. I'm not sure of the best approach to achieve this. Ideally, the clicked elements should be present in both URLs (part ...

Ensuring compatibility of peerDependencies through devDependencies in npm3

With the recent update to NPM 3, automatic resolving of peer dependencies has been removed. This poses a challenge when developing a plugin/library for consumption by another application. If the underlying library uses peerDependencies, it requires manual ...

Finding the title of a checkbox within a specific row

I am facing an issue where I have a checkbox inside a grid, and I need to determine the header name of that specific element upon clicking a button located outside the grid. The structure of my grid is as follows: <thead class="k-grid-header"> &l ...

Building connections in parse.com using various classes (JavaScript SDK)

Currently using parse.com in conjunction with the JavaScript SDK. Despite my extensive research, I have been unable to find any examples that directly address the issue I am facing. Here is the specific goal I am striving to accomplish: I aim to establi ...

NodeJs:- Retrieve data from the initial dropdown menu and display it dynamically in the secondary dropdown

Currently, I am working on a dropdown list and facing an issue where the results displayed in the second dropdown need to be filtered based on the selection made in the first dropdown. The EJS code snippet that I am using is: <div class="form-group"& ...