简体   繁体   English

如何仅在模板中加载Google Maps JavaScript?

[英]How to load google-maps javascript in template only?

I'm using google maps javascript api, and would like to load the javascript file only on the page where the map is actually displayed. 我正在使用google maps JavaScript API,并且只想在实际显示地图的页面上加载JavaScript文件。

When I load the maps within <script> in index.html , everything is fine. 当我在index.html <script>中加载地图时,一切都很好。

<body>
    <div ng-view></div>

    <script>...</script>
</body>

But when I move the script to the template that is to be included, it does not work: 但是,当我将脚本移动到要包含的模板时,它不起作用:

maps.html: maps.html:

<div id="google-map">
    ...
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>

controller: 控制器:

var gmap = new google.maps.Map(document.getElementById('google-map'), {
    center: location,
    zoom: 10
});

Result: Error: google.maps is undefined . 结果: Error: google.maps is undefined

Question: how can I ensure the script is loaded only on the desired page, and that it is loaded before the instantiate in the controller takes place? 问题:如何确保仅在所需页面上加载脚本,并且确保在controller实例化之前加载脚本?

need to add script tag before div, hope this may works 需要在div之前添加脚本标签,希望这可以工作

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<div id="google-map">
    ...
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM