Google Maps API dynamic load with AngularJS

烈酒焚心 提交于 2019-12-20 07:06:42

问题


I'm trying to load Google Maps API using AngularJS:

<html data-ng-app="search-app">
<head data-ng-controller="GoogleMaps">
    <script ng-src="{{mapsUrl}}" type="text/javascript"></script>
....
</head>

and controller for that part:

search.controller('GoogleMaps', [
    '$scope','$sce',
    function GoogleMaps($scope,$sce) {
        var mapsUrl = '//maps.google.com/maps/api/js?sensor=false&key=my_api_key';
        $scope.mapsUrl = $sce.trustAsResourceUrl(mapsUrl);
    }
]);

but when the Google Map API is called within the search controller it throws and error

this.setMap is not a function

for

function CustomMarker(latlng, map, args) {
    this.latlng = latlng;
    this.args = args;
    this.setMap(map);
}

but when I will replace {{mapsUrl}} with full URL in the HTML header it will works.

Any thoughts on that?


回答1:


I have ended up appending URL to the header as a script on load event

function require(url, callback)
{
    var element = document.createElement("script");
    element.src = url;
    element.type="text/javascript";
    element.addEventListener('load', callback);
    document.getElementsByTagName("head")[0].appendChild(e);
}


来源:https://stackoverflow.com/questions/53675172/google-maps-api-dynamic-load-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!