rocinante rocinante - 19 days ago 5
Javascript Question

google is not defined when trying to initialize google maps via the object literal pattern

i'm trying to get to grips with the object literal pattern by making a simple website using it. A part of this website is a contact us page that includes a map, which I'm trying to initialise using the pattern. Simple stuff, or so I thought. So the mapControl.init() function is the one that's throwing the error and I just can't figure out why. If i use the initMap() function it works.

var mapControl = {
lat: 52.626562,
long: -8.664159,
$map: $('#map'),
zoom: 8,
defaultUiOff: true,
init: function () {
var map;
map = new google.maps.Map(mapControl.$map, {
center: { lat: mapControl.lat, lng: mapControl.long },
zoom: mapControl.zoom,
disableDefaultUI: mapControl.defaultUiOff
});
}
}

mapControl.init();

function initMap() {
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 52.626562, lng: -8.664159 },
zoom: 15,
disableDefaultUI: true
});
}


Any help would be much appreciated

Answer

$('#map') returns an array, the google maps API expects a single HTML element, use:

$map: $('#map')[0],

proof of concept fiddle

code snippet:

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<script>
  var mapControl = {
    lat: 52.626562,
    long: -8.664159,
    $map: $('#map')[0],
    zoom: 8,
    defaultUiOff: true,
    init: function() {
      var map;
      map = new google.maps.Map(mapControl.$map, {
        center: {
          lat: mapControl.lat,
          lng: mapControl.long
        },
        zoom: mapControl.zoom,
        disableDefaultUI: mapControl.defaultUiOff
      });
    }
  }
  mapControl.init();
</script>

Comments