【问题标题】:Google Maps for Angular directive not working in functionGoogle Maps for Angular 指令不起作用
【发布时间】:2014-09-20 00:33:54
【问题描述】:

我试图在另一个函数中使用这个Google Maps for AngularJS 指令。当我将 $scope.map 移到函数调用之外并静态设置纬度/经度时,该代码有效。但是,我想要做的是在我的函数调用中动态设置纬度/经度。 代码如下。

html:

<google-map center="map.center" zoom="map.zoom"></google-map>

角度控制器:

angular.module('StadiumCtrl', []).controller('StadiumController', function($scope, $rootScope, $routeParams, $sce, Stadia, Instagram, Weather) {

// pull stadium details from API based on routeParams
$scope.id = $routeParams.id;

Stadia.get($scope.id).success(function(response) {
    $rootScope.logo = response.logo;

    $scope.homeColors = {
        "border": "2px solid " + response.sec_hex,
        "box-shadow": "3px 3px 7px " + response.prim_hex,
        "margin": "6px",
        "padding": "0"
    }

    $scope.map = {
        center: {
            latitude: response.loc[1],
            longitude: response.loc[0]
        },
        zoom: 8
    };

    // pass loc_id into Instagram API call
    Instagram.get(response.loc_id).success(function(response) {
        instagramSuccess(response.loc_id, response);
    });

    // pass city and state into Wunderground API call
    Weather.get(response.city, response.state).success(function(response) {
        $rootScope.temp = Math.round(response.current_observation.temp_f);
    });

// Instagram API callback
var instagramSuccess = function(scope,res) {
    if (res.meta.code !== 200) {
        scope.error = res.meta.error_type + ' | ' + res.meta.error_message;
        return;
    }
    if (res.data.length > 0) {
        $scope.items = res.data;
    } else {
        scope.error = "This location has returned no results";
    }
};
});

【问题讨论】:

    标签: javascript angularjs google-maps-api-3


    【解决方案1】:

    看起来 google-maps 指令在链接指令时需要一个初始值。一旦有了默认值,它将响应该范围值的变化。

    您可以使用以下代码看到这一点:

    $scope.map = {center: {latitude:0,longitude:0}, zoom: 0};
    
    $timeout(function() {
        $scope.map = {center: {latitude: 51.219053, longitude: 4.404418 }, zoom: 14 };
    }, 1000);
    

    http://plnkr.co/edit/szhdpx2AFeDevnUQQVFe?p=preview 进行了演示。如果您在 $timeout 之外注释掉 $scope.map 分配,则地图将不再显示,但如果您将第 3 行放回原处,它将在 $timeout 执行时更新地图。

    在您的情况下,您应该可以简单地添加

    $scope.map = {
        center: {
            latitude: 0,
            longitude: 0
        },
        zoom: 0
    };
    

    就在你运行Stadia.get($scope.id).success(function(response) {之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      相关资源
      最近更新 更多