ArjanSchouten
ArjanSchouten

Reputation: 1368

Google Maps Api v3 marker. google is undefined

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?

Upvotes: 2

Views: 9855

Answers (2)

geocodezip
geocodezip

Reputation: 161384

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>

Upvotes: 7

Andy
Andy

Reputation: 63550

You're defining your map variable locally within initialize which means that none of the other functions can access it. Declare it globally outside of initialize:

var map;

function initialize() {
  // code
  map = new google.maps.Map(document.getElementById('maps', mapOptions);
}

Upvotes: 0

Related Questions