文件之间的Javascript var

时间:2016-04-07 11:32:53

标签: javascript node.js google-maps geolocation

我在将变量导入js函数从回调中运行时出现问题:

<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>

问题是我不能在initMap中使用全局变量或外部函数。我正在使用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);
        }
    });
}

当地址取自html表格或可以明确定义时:

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

但是我需要能够使用全局变量或导出的函数:

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

我不明白异步足以能够做到这一点

1 个答案:

答案 0 :(得分:0)

您可以使用窗口并为要全局访问的变量创建命名空间。

请在Storing a variable in the JavaScript 'window' object is a proper way to use that object?中查看Blazemonger的回答。

我想,这会帮助你想去的地方。

您可以添加动态脚本加载功能,如下所示:

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

loadjs(&#34; myscript.js&#34)