Getting “Uncaught ReferenceError: google is not defined” error using Google Maps API

If you are loading the API asynchronously (with async, defer, &callback=initMap), you need to put all code that depends on the API inside the callback function (or at least somewhere where it won’t execute until the API has loaded). Right now your myCenter variable is defined outside the callback function.

Change:

<script type="text/javascript"'>
var myCenter = new google.maps.LatLng(29.714954,32.368546);
function initMap() {

To:

<script type="text/javascript"'>
function initMap() {
  var myCenter = new google.maps.LatLng(29.714954,32.368546);

proof of concept fiddle

code snippet:

html,
body,
#map-container,
.map,
.container {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<header id="masthead" class="site-header" role="banner">
  <div class="top-strip"></div>
  <div class="top-nav"></div>
</header>

<section class="container">
  <section class="map">
    <div id="map-container"></div>
    <div class="contact-container">
      <div class="contact">
        <img src="" alt="mail-icon">
        <span>You can contact us at [email protected]</span>
      </div>
    </div>
  </section>
</section>
<div id="footer-container">
  <footer id="footer">
  </footer>
</div>
<script type="text/javascript">
  function initMap() {
      var myCenter = new google.maps.LatLng(29.714954, 32.368546);
      var mapProp = {
        center: myCenter,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("map-container"), mapProp);
      var marker = new google.maps.Marker({
        position: myCenter,
        title: "AZHA"
      });
      marker.setMap(map);
      var infowindow = new google.maps.InfoWindow({
        content: "AZHA"
      });
      infowindow.open(map, marker);
    }
    // google.maps.event.addDomListener(window, 'load', initMap);
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>

Leave a Comment