Issue with Google Maps Angular directive failing to function correctly

Trying to implement the Google Maps for AngularJS directive within a function has been a challenge. I've managed to make it work by moving $scope.map outside the function call and setting the lat/lon statically. However, my goal is to dynamically set the lat/lon within the function call. See code snippet 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) {

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

Answer №1

To ensure the google-maps directive functions correctly, it is important to provide an initial value when linking the directive. Once a default value is set, the directive will be able to respond to changes in that scope value.

An example demonstrating this concept can be seen in the code below:

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

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

This demonstration can be viewed at http://plnkr.co/edit/szhdpx2AFeDevnUQQVFe?p=preview. If you remove the assignment of $scope.map outside the $timeout, the map will not display. However, if you reintroduce line 3, the map will update when the $timeout function runs.

In your specific scenario, simply add the following code snippet before executing

Stadia.get($scope.id).success(function(response) {
:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to extract a value from a JSON object?

I am having trouble deleting data from both the table and database using multiple select. When I try to delete, it only removes the first row that is selected. To get the necessary ID for the WHERE condition in my SQL query, I used Firebug and found this P ...

disable full page scrolling on iOS devices

Can you achieve elastic scrolling for a single absolutely positioned div in Mobile Safari without causing the entire page to move up and down? Check out this basic example that illustrates the problem: <!doctype html> <html> <head> ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

Adding angular-scenario.js to my Rails Jasmine tests is causing them to malfunction and not run properly

I'm currently working on a simple website with a Rails back end and an AngularJS front end. I have Jasmine tests set up, but when I try to include angular-scenario.js for end-to-end testing, my tests don't even run. They simply refuse to start. ...

AngularJS and Bootstrap collaboration creates a stylish oblique design

Can an oblique stripe be made with angularJS and Bootstrap? See image for reference. https://i.stack.imgur.com/v3kEQ.png ...

Tips on waiting for an event to be processed during a Protractor end-to-end test

I have a straightforward AngularJs 1.4.8 Front-End: https://i.stack.imgur.com/2H3In.png After filling out the form and clicking the OK button, a new person is added to the table. The form resides in the addingPersonController, while the table is control ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...

The audio stops when the ngaudio screen is clicked

When it comes to playing audio using the ngAudio service in AngularJS 1, the following code snippet is commonly used: $scope.audio = ngAudio.load("abc.wav"); $scope.audio.play(); However, some users have reported that after the sound is played, clicking ...

Observing the Transformation When Employing *ngIf or *ngSwitchCase in Angular 2

Can someone lend a hand? I've run into an issue where my custom JavaScript function is not working after using *ngIf or *ngSwitchCase to change the view. Any suggestions on how to resolve this would be greatly appreciated. ...

Is it possible to trigger an ajaxcall once another one has finished executing?

Just curious, do you think the code snippet below is capable of triggering a second ajax function once the first one has completed successfully? if(xmlHttp) // xmlHttp represents an XMLHttpRequest object { xmlHttp.onreadystatechange = function() ...

Issue with display of animation on MUI TextField

I'm facing an issue with my TextField component. I have a placeholder and value set up, but when I insert an icon using the InputProps prop, the animation that normally changes from placeholder to value doesn't appear. However, if I remove InputP ...

Using an Ajax call to show a date picker when a button is clicked

I've created buttons for each ID in the "habitaciones" table. When a button is clicked, it should display a specific datepicker with dates disabled for that ID. To achieve this, I utilized an Ajax function where the form should be displayed based on ...

Browsing JSON data to pinpoint locations on a Google map

Trying to create a google map using jQuery and javascript with latitude and longitude values stored in a JSON file. Clicking on a state name should generate the map. Encountering an issue where only index[0] is being generated. The for loop seems to be ma ...

Executing JavaScript code within a Django application to load a file

Utilizing a JavaScript tool called jQuery FileTree within my Django application has presented a dilemma. This particular JavaScript requires access to a python script path, but incorporating Django template tags directly into JavaScript poses an issue. Wi ...

Do I have to rewrite my Protractor tests if I update AngularJS?

Recently, I developed a web application using AngularJS v1.5.8 and now considering implementing testing with protractor. However, my concern is if I decide to upgrade Angular in the future, will I encounter any compatibility issues that require me to rewri ...

I am looking to view all products that belong to the category with the ID specified in the request, and have red-colored stocks

Within my database, I have defined three mongoose models: Product, Category, and Stock. The Product model contains two arrays - categories and stocks, each including respective category and stock ids. My goal is to retrieve all products where the category_ ...

Converting the Python/Flask Backend into a Vue.js Frontend Interface

Recently, I delved into the world of frontend to backend communications. To learn more about this concept, I decided to create a small backend program using the boto3 module in Python to fetch data. The backend program I created is functioning perfectly w ...

The search filter implemented in the ng-if directive in AngularJS seems to be malfunctioning

I've been using the angularjs search filter and it was working well. However, I wanted the search box to only appear in the Cars list. So, I added ng-if="key=='Cars'" to the search box. But strangely, after adding the ng-if, the filter stopp ...

Issue with repeated items in Flatlist

Whenever I display my flatlist, it appears to be duplicating the items within it (the feedCache has only one index but the data for this index is rendered twice). Below is the code snippet for the flatlist: const FeedBody = React.memo(() => { return ...

How can one transform an array (in the form of a JSON array) into a map?

After running my script, I receive an array (JSON Array) structured like this: [{redirectCount=0, encodedBodySize=60962, unloadEventEnd=0, responseEnd=1601.699999999255, domainLookupEnd=995.7999999896856, ... Now, I want to display the key-value pairs fr ...