An error was encountered: ReferenceError - Unable to locate google within the google.maps.Marker() function

<script src="https://maps.googleapis.com/maps/api/js?key=[KEY]&callback=initMap"
            async defer></script>
    <script>
            var user_lat,user_lng;
            var map;
            function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                            center: {lat:17, lng: 80},
                            zoom: 5
                            });
            }
            var marker = new google.maps.Marker({
                position: {lat:17,lng:80},
                map: map,
                title: 'Hello World!'
            }); 
    </script>

This scenario is being tested for validation. The intention is to implement this logic in a different piece of code. Assistance on this matter would be greatly appreciated.

It's possible that this situation has been discussed before. Despite similar issues reported in other threads, none of the solutions provided have resolved my specific problem.

The map loads successfully without any issues. The `initMap()` function executes as expected. However, the marker component does not appear on the map.

Answer №1

When using the async and defer attributes, the execution of the api library is deferred. This means that when the marker is being defined, the browser may not have loaded the library yet, causing google.maps.Marker to be undefined.

To fix this issue, move the code where the marker is defined inside the initMap() function.

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVD0ngfhOFs5rnww7UFyz9rN6UznOIZ1U&callback=initMap" async defer></script>
<script>
  var user_lat,user_lng;
  var map;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat:17, lng: 80},
      zoom: 5
    });
    var marker = new google.maps.Marker({
      position: {lat:17,lng:80},
      map: map,
      title: 'Hello World!'
    }); 
  }
</script>

var user_lat, user_lng;
var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 17,
      lng: 80
    },
    zoom: 5
  });
  var marker = new google.maps.Marker({
    position: {
      lat: 17,
      lng: 80
    },
    map: map,
    title: 'Hello World!'
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<div id="map"></div>

Answer №2

By adding the async attribute to your script, you are indicating that the browser should not wait for it to finish loading.

However, when you try to execute new google.maps.Map(), the script may not have finished loading yet, causing the execution to fail. To fix this, remove the async defer attributes from the script tag and load it synchronously.

If you still want the script to be loaded asynchronously, consider using a callback function instead.

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

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below: <template> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> < ...

Tips for incorporating a multimedia HTML/JavaScript application within C++ programming

I possess the source code for a JavaScript/HTML5 application that operates on the client-side and manages the transmission/reception of audio and video data streams to/from a server. My objective is to develop a C++ application that fully integrates the c ...

Ensure that the function's parameters are entered exclusively through TypeScript interfaces

How can I efficiently organize and maintain the function's arguments below without utilizing Typescript? Can this be achieved using Interfaces? // external file export interface TSomeFunctionArgs { someKey: string // there should also be a type ...

Gulp: executing a task with no specified output location

I am attempting to create a straightforward task to display the file size for each file in an array of paths using the gulp-size plugin, as shown below: var gulp = require('gulp') var size = require('gulp-size') gulp.task('size&a ...

What steps can be taken to enable JSONIX to handle additional XML elements during the deserialization process?

JSONIX 2.0.12 is truly impressive. I am working with a substantial XML file and I am only looking to convert certain elements into JSON format. Whenever I omit some elements from my mapping file, JSONIX throws an unexpected element error during deseriali ...

Tips for creating multiple full-screen overlays in HTML

I am new to the world of web development and I am currently working on implementing a set of buttons that will trigger specific overlays when clicked. I found the following code snippet on W3schools which creates a button along with an overlay effect. < ...

Overlaying a div on top of an iframe

Struggling to make this work for a while now. It seems like a small issue related to CSS. The image isn't overlaying the IFrame at the top of the page as expected, it's going straight to the bottom. Here is the code snippet: .overlay{ width: ...

Having trouble with preventDefault() not working during a keyup event?

I am struggling to make preventDefault() function properly. Here are a few variations of the code that I have attempted: First: $(document).keyup(function (evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode == 192) { ...

Creating DIV's with Equal Heights Using AngularJS ng-repeat

I'm currently facing an issue with aligning two side-by-side divs to the same height when the content is generated using an ng-repeat function. Using flexbox is causing responsiveness issues, and I'm unsure of the appropriate time to call a jQuer ...

Transforming JSON data from a Javascript object into Ruby

When I send an object from Javascript to a Sinatra POST route, I use the 'stringify' method to convert the JS object to JSON. The JSON that is being sent looks like this (based on the Chrome developer tools): {"a":1,"b":2,"c":"3"}: In my Sinatr ...

The AngularJS promise is not resolving before the external Braintree.js script finishes loading after the HTML content has been fully

Using an external braintree.js script is necessary to generate a payment widget, and unfortunately I have no control over it. The code that needs to be included in my .html page is as follows: <div id="myClient" ng-show="false">{{myClientToken}}&l ...

How can I replicate the functionality of a div mimicking a select element using javascript upon clicking away from the element?

My task was to design a pseudo-select element that showcases columns for each row within the select. Due to HTML's restriction on allowing the <option> tag to include HTML, I had to find an alternate solution. One issue I encountered was replic ...

What's the best way to ensure uniform spacing between the list items in this slider?

When using appendTo, I've noticed that the spacing between items disappears. I've tried adjusting the padding-bottom and left properties with no success. Does anyone have a suggestion for how to fix this issue? I'm at a standstill. $(&a ...

Can you explain the purpose of $winstonLoggerConfig<T>() and $winstonLogger<T>() in winston v3?

I'm currently using the winston logger and I want to implement flow typing for it. However, I am unsure of what exactly I should pass to it in order to achieve this. Below is my current logger setup: const logger = createLogger({ ... }); Missing typ ...

The onblur function is not being triggered

Recently, I encountered an issue while trying to invoke a JavaScript function onblur of a field. The main problems I faced were: 1) The popup inside the function call was triggered automatically during page load. 2) When attempting to access the functio ...

Saving Information to a Specific Location on the Client Side in a CSV File

I am currently working on a static application that uses Angular JS technology. My goal is to write data into a CSV file at a specific path in order for another API to read the data from that location. Despite searching extensively on the internet, I hav ...

Utilizing @Material-UI Tabs for a Stylish Navigation Bar

As a newcomer to the coding realm, I find myself on a quest for an answer that has proven elusive. Despite scouring various sources, none of the solutions I've stumbled upon seem to work in my case. The issue at hand revolves around my desire to util ...

Regulation specifying a cap of 100.00 on decimal numbers entered into a text input field (Regex)

I have created a directive that restricts text input to only decimal numbers in the text field. Below is the code for the directive: import { HostListener, Directive, ElementRef } from '@angular/core'; @Directive({ exportAs: 'decimal ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...