I'm getting a strange behavior with CoffeeScript: the
initMap
&callback=initMap
initMap()
# Declare a global function
@initMap = ->
restaurantLocation =
lat: $('#restaurant-map').data("lat")
lng: $('#restaurant-map').data("lng")
map = new (google.maps.Map) $('#restaurant-map')[0],
zoom: 19,
center: restaurantLocation
marker = new (google.maps.Marker)
position: restaurantLocation
map: map
$(document).on 'turbolinks:load', ->
if $('#restaurant-map').length > 0
if page.included_google_maps_js_api == undefined
google_maps_api_key = 'xxx'
# correctly called from here...
$.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
page.included_google_maps_js_api = true
initMap() # Uncaught ReferenceError: google is not defined
$(document).on 'turbolinks:load', ->
if $('#restaurant-map').length > 0 && page.included_google_maps_js_api == undefined
google_maps_api_key = 'xxx'
$.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
page.included_google_maps_js_api = true
else if ($('#restaurant-map').length > 0)
initMap()
$.getScript
gets the script asynchronously. You're not waiting for the result of that before calling initMap
in the case where page.included_google_maps_js_api == undefined
is true.
You just need an else
(since you're using &callback=initMap
to call it in the case where need to load):
$(document).on 'turbolinks:load', ->
if $('#restaurant-map').length > 0
if page.included_google_maps_js_api == undefined
google_maps_api_key = 'xxx'
# correctly called from here...
$.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
page.included_google_maps_js_api = true
else # <== Note the else
initMap() # so we only do this if it's loaded