Google Maps Api v3 marker. google is undefined

google-maps, google-maps-api-3, javascript

Solution

You can't use the Google Maps Javascript API v3 until it is loaded. Your marker creation is running before the API is loaded. You need to move it in to the initialize function, which won't execute until the API is available.

<script>

function initialize() {

  var mapOptions = {
    zoom: 10,
    center: new google.maps.LatLng(51.817116, 4.780616),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    panControl: false,
    mapTypeControl: false,
    scaleControl: false,
    streetViewControl: false,
    overviewMapControl: false,
    rotateControl: false
  };

  var map = new google.maps.Map(document.getElementById('maps'),
  mapOptions);

  var customMarker = new google.maps.Marker({
    position: new google.maps.LatLng(51.817116, 4.780616),
    map: map
  });

};  // end of initialize


function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3&sensor=false&' +
    'callback=initialize';
  document.body.appendChild(script);
}

addLoadEvent(loadScript);

</script>

Problem

I've a website with the google maps api which is loaded asynchronous. But this throws a errer: google is not found. My code is: ``` <script> function initialize() { var mapOptions = { zoom: 10, center: new google.maps.LatLng(51.817116, 4.780616), mapTypeId: google.maps.MapTypeId.ROADMAP, panControl: false, mapTypeControl: false, scaleControl: false, streetViewControl: false, overviewMapControl: false, rotateControl: false }; var map = new google.maps.Map(document.getElementById('maps'), mapOptions); }; var customMarker = new google.maps.Marker({ position: new google.maps.LatLng(51.817116, 4.780616), map: map }); function loadScript() { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3&sensor=false&' + 'callback=initialize'; document.body.appendChild(script); } addLoadEvent(loadScript); </script> ``` When I delete the marker the code works correctly. Why is'nt it working if I add the marker as specified in some examples? The addLoad is a load event. That's not the problem... Can anybody help me to get this working?

Original source