Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 900
Krishna Avatar asked Sep 11 '26 09:09

Krishna


1 Answers

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>
like image 199
Lucius Avatar answered Sep 13 '26 22:09

Lucius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!