0

I am having problems importing a variable into a js function run from a callback as:

<script type="text/javascript" src="/javascripts/maps.js"> </script>

  <script async defer
          src="https://maps.googleapis.com/maps/api/js?key=<%= mapkey%>
        &libraries=visualization&callback=initMap">
  </script>

The problem is I cannot use a global variable or external function inside initMap. I am using nodejs.

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: {lat: -34.397, lng: 150.644}
    });
    var geocoder = new google.maps.Geocoder();

    document.getElementById('submit').addEventListener('click', function() {
        geocodeAddress(geocoder, map);
    });
}

function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('address').value;
    geocoder.geocode({'address': address}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: resultsMap,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

As the moment the address is taken from the html form or can be explicitly defined:

var address = document.getElementById('address').value; or
var address = ["place", "place"]

However I need to be able to use a global variable or an exported function:

var address = global_locations (defined elsewhere as a global.gobal_locations = ["place", "place"] and works in other files) or
var address = loc.getAddresses();

I dont understand async enough to be able to do this

user1212520
  • 501
  • 1
  • 5
  • 15

1 Answers1

0

You could use window and create a namespace for your variables which you want to access globally.

Please check this answer from Blazemonger in Storing a variable in the JavaScript 'window' object is a proper way to use that object?.

This will help you where you want to go, I think.

You can add a dynamic script loading function, like this:

function loadjs(filename){
    var jsfile=document.createElement('script')
    ref.setAttribute("type","text/javascript")
    ref.setAttribute("src", filename)
}

loadjs("myscript.js")

Community
  • 1
  • 1
Ederico Rocha
  • 250
  • 4
  • 10