Ionic - 控制器中的调用函数导致ReferenceError:google未定义

时间:2017-08-07 12:20:41

标签: angularjs ionic-framework geolocation

我刚刚开始练习离子,真的很酷。我遇到的错误是ionic.bundle.js:26799 ReferenceError: google is not defined。我有一个应用程序,我称之为位置getter。其目的是在应用加载时显示用户位置,点击banksschools后,它会显示半径为25公里的当前位置周围的banksschools。我已成功完成此操作,但问题是当我的应用加载时,它不会显示地图,除非我按下find me按钮。之后它完美无缺。但我不想使用find me按钮。我想要的是,当控制器加载时,find me函数自动调用,然后在所有操作之后,我不想每次都重新加载地图。但是当我在控制器中调用find me函数时,它会给出这个便宜的错误。我怎么解决这个问题?我尝试了许多方法,例如在我的index文件中安排javascript文件,尝试使用init。但没有成功。

以下是 controller.js

的代码
app.controller('main', function($scope) {
var map, infoWindow;

$scope.initLocation = function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: -34.397,
            lng: 150.644
        },
        zoom: 15
    });
    infoWindow = new google.maps.InfoWindow;

    //  Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            $scope.position_lat = position.coords.latitude;
            $scope.position_long = position.coords.longitude;
            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn 't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
    infoWindow.open(map);
}

//  var map;
// var infowindow;

function initMap(place_name) {
    var pyrmont = { lat: $scope.position_lat, lng: $scope.position_long };

    map = new google.maps.Map(document.getElementById('map'), {
        center: pyrmont,
        zoom: 15
    });

    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch({
        location: pyrmont,
        radius: 25000,
        type: [place_name]
    }, callback);
}

function callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
        }
    }
}

function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
    });
}



$scope.show_places = function(place_name) {
    initMap(place_name);
}

});

这是我的 index.html

  <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <style>
        #map {
            height: 100%;
        }

        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controller.js"></script>

</head>

<body ng-app="starter">

    <ion-pane>
        <ion-header-bar class="bar-stable">
            <h1 class="title">Location Finder</h1>
        </ion-header-bar>
        <ion-nav-view></ion-nav-view>

        <div class="bar bar-footer bar-assertive" ng-controller="main">
            <div class="button-bar">
                <button class="button button-positive" ng-click="show_places('bank')">Banks</button>
                <button class="button button-energized " ng-click="show_places('school')">Schools</button>
                <button class="button button-positive " ng-click="initLocation() ">Find me</button>
            </div>
        </div>
    </ion-pane>
</body>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=mykey_Q&libraries=places ">
</script>

</html>

1 个答案:

答案 0 :(得分:0)

当谷歌的库尚未加载时,通常会发生该错误,您必须等待加载它们。这就解释了当您点击MKMapView按钮时它的工作原理。

findMe参数添加到Google地图网址:

callback

加载库后,向app.js中的控制器广播一个事件:run():

<script async defer src="https://maps.googleapis.com/maps/api/js?key=mykey_Q&libraries=places&callback=googleMapsReady">

并在你的控制器内:

.run($rootScope, ...){
    window.googleMapsReady = function(){
        $rootScope.broadcast('google-maps-ready');
    }
}

顺便说一句,您在initMap()和initLocation()中创建了两次映射。只需在一个地方创建它,然后重复使用它。