MattDionis
MattDionis

Reputation: 3616

Google Maps for Angular directive not working in function

I'm attempting to use this Google Maps for AngularJS directive inside another function. The code works when I move $scope.map outside the function call and set the lat/lon statically. However, what I want to do is set the lat/lon dynamically within my function call. Code below.

html:

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

Angular controller:

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";
    }
};
});

Upvotes: 1

Views: 329

Answers (1)

jkjustjoshing
jkjustjoshing

Reputation: 3630

It looks like the google-maps directive needs an initial value when the directive gets linked. Once there is a default value it will respond to changes in that scope value.

You can see this in action with the following code:

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

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

which is demonstrated at http://plnkr.co/edit/szhdpx2AFeDevnUQQVFe?p=preview. If you comment out the $scope.map assignment outside the $timeout the map will no longer show up, but if you put line 3 back it in will update the map when the $timeout executes.

In your case, you should simply be able to add

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

just before you run Stadia.get($scope.id).success(function(response) {.

Upvotes: 1

Related Questions