Krishna
Krishna

Reputation: 621

Uncaught ReferenceError: google is not defined at google.maps.Marker()

<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 is for testing purpose. I have to use this concept in another code. kindly help this.

This may be found as duplicate. There are many other posts which report same error, but none of the answers solved my problem.

Map is loading without any problem. initMap() function is executed. But the marker part is not coming.

Upvotes: 3

Views: 27550

Answers (2)

Lucius
Lucius

Reputation: 2872

Since you have async and defer attributes, execution of the api library is deferred. When marker is being defined, the browser still haven't load the library, so google.maps.Marker is not defined.

Move the code where marker is defined inside initMap() function and it should work.

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

Upvotes: 11

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34234

You load your script with async flag. It means that a browser will not wait until this script will finish loading.

At the time of executing your new google.maps.Map(, it is still not loaded, and execution fails. Remove async defer flags from your script tag and make it load synchronously.

If you want the script to be loaded asynchronously, you need to use callback function.

Upvotes: 2

Related Questions