The Angular directive is failing to refresh the data on the Google Map

I created a directive called "myMap" to incorporate a Google map into my application. However, I am facing an issue when attempting to update the longitude and latitude values for a different location using a controller function. The directive does not reflect the updated values, and the same map is being displayed.

Below is my Directive code:

directive('myMap', function () {
    // directive link function
    var link = function (scope, element, attrs) {
        var map, infoWindow;
        var markers = [];

        // map configuration
        var mapOptions = {
            center: new google.maps.LatLng(attrs.latitude, attrs.longitude),
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false
        };

        // initialize the map
        function initMap() {
            if (map === void 0) {
                map = new google.maps.Map(element[0], mapOptions);
            }
        }

        // add a marker
        function setMarker(map, position, title, content) {
            var marker;
            var markerOptions = {
                position: position,
                map: map,
                title: title,
                icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png',
                animation: google.maps.Animation.Bounce

            };

            marker = new google.maps.Marker(markerOptions);
            markers.push(marker); 

            google.maps.event.addListener(marker, 'click', function () {
             
                if (infoWindow !== void 0) {
                    infoWindow.close();
                }
                var infoWindowOptions = {
                    content: content
                };
                infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                infoWindow.open(map, marker);
            });
        }

        
        initMap();

        setMarker(map, new google.maps.LatLng(attrs.latitude, attrs.longitude), attrs.restname, attrs.address);

    };

    return {
        restrict: 'A',
        template: '<div id="gmaps"></div>',
        replace: true,
        link: link
    };
});

Next, I include this directive in my HTML as shown below:

<div class="gmaps"   my-map="" latitude="{{home.latitude}}" longitude="{{home.longitude}}"></div>

I have tried various methods to resolve this issue without success. How can I monitor changes in the directive parameters to track updates in longitude and latitude values? Any assistance would be greatly appreciated.

Answer №1

Make sure to include a watcher in your directive.

 attrs.$observe("value", function (data) {},true);

The watcher will detect any changes in the parameters of the directive and update them accordingly.
In your specific case, it should look something like this:

lahorefoodsWebSiteModule.directive('myMap', function () {
// directive link function
var link = function (scope, element, attrs) {
    attrs.$observe("latitude", function (latitude) {
        // This function is called when the data changes.

    var map, infoWindow;
    var markers = [];

    // map configuration
    var mapOptions = {
        center: new google.maps.LatLng(attrs.latitude, attrs.longitude),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    };

    // initialize the map
    function initMap() {
        if (map === void 0) {
            map = new google.maps.Map(element[0], mapOptions);
        }
    }

    // place a marker on the map
    function setMarker(map, position, title, content) {
        var marker;
        var markerOptions = {
            position: position,
            map: map,
            title: title,
            icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png',
            animation: google.maps.Animation.Bounce

        };

        marker = new google.maps.Marker(markerOptions);
        markers.push(marker); // add marker to array

        google.maps.event.addListener(marker, 'click', function () {
            // close infowindow if not undefined
            if (infoWindow !== void 0) {
                infoWindow.close();
            }
            // create a new infowindow
            var infoWindowOptions = {
                content: content
            };
            infoWindow = new google.maps.InfoWindow(infoWindowOptions);
            infoWindow.open(map, marker);
        });
    }

    // display the map and add some markers
    initMap();

    setMarker(map, new google.maps.LatLng(attrs.latitude, attrs.longitude), attrs.restname, attrs.address);
    },true);
};

return {
    restrict: 'A',
    template: '<div id="gmaps"></div>',
    replace: true,
    link: link
};

});

Your HTML code remains the same. This should help resolve the issue you are facing.

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

Arrange an array by the occurrence rate of its elements within objects contained in another array, using Javascript

I found the explanation to be rather complex. Essentially, my goal is to iterate through each object in the 'objects' array, analyze the 'choice' values, tally the frequency of each letter, and then arrange the original arrays based on ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

the router is having trouble choosing the right function

When attempting to log in a user using postman with the URL http://localhost:3000/login, it seems to always trigger the register function instead. The code itself is working fine, but it's just routing to the wrong function. How can I redirect it to t ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed. I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM. To achieve this, I have been using .append() to ...

Deleting a row from a table in AngularJS can be accomplished by following these steps

I am having trouble with deleting rows from a table using angularjs. When I try to delete a row, it ends up deleting the previous row instead of the correct one. How can I fix this issue? Please check out the working DEMO Here is the code snippet: < ...

Issue with Firefox-Android causing dropdown toggle to malfunction

When I manually trigger a dropdown, it closes when any click is performed outside of it (while open). This code works in all browsers except for Firefox on Android. Why does this happen? It seems like the event parameter doesn't reach the function ...

Multi selection dropdown feature in Angular failing to populate the options

I am working on a small Angular controller that manages a dropdown menu, with the second dropdown menu populating based on the selection made in the first one. Despite my best efforts, I can't seem to populate the dropdown menus with any content from ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

The global CSS styles in Angular are not being applied to other components as expected

Currently utilizing Angular v10, I have a set of CSS styles that are meant to be used across the entire application. To achieve this, I added them to our global styles.css file. However, I'm encountering an issue where the CSS is not being applied to ...

What is the best way to pass ng-model value from directive to controller in Angular?

I recently developed a custom directive which includes a text box. I am facing difficulties in retrieving the value of the model associated with it in my controller. Despite my efforts, I have not been successful. Below is the code for my directive: app. ...

Using file types in Vue 3: a beginner's guide

In order to use file-type to determine not only the extension but also ensure the headers are correct I would need to use one of the methods listed on their GitHub page. In version 19.0.0 it says fileFromFileType doesn't have such an export and in 16. ...

Is there a way to dynamically compute the height of rows in a VariableSizeList based on their index?

Is there a method to dynamically calculate the height of rows in React using the react-window library? Since it's uncertain whether all rows will have the same size, I find myself needing to utilize VariableSizeList. However, I'm wondering if the ...

Interactive form found on a webpage

Hey there! I'm currently working on a task where I want a form to be displayed when the edit button is clicked. Once the save button in the form is pressed, I want to update my database with the new information. It's crucial that this process hap ...

Clicking on the ajax tab control in asp.net displays a single rectangular box - how can this be removed?

When using tab control in Ajax, I encountered an issue where a blue rectangle box appeared when clicking or opening the page. How can I remove this unwanted box? ...

Looking to pass a confidential input parameter to a MVC controller via AngularJS

I'm trying to figure out how to pass a hidden input field value to my MVC controller. $http({ method: 'GET', url: '/User/GetProjectsList' }) .success(function (data, status, headers, config) { $scope.workflow = []; ...

Dynamic styling updates on page refresh in Next.js

There is a strange issue with my styling that I can't seem to figure out. I have a NavBar set to be 20vh in height and an image set to be 100% in width. However, whenever I refresh the page, the NavBar height decreases and the image width increases si ...

Having issues displaying the & symbol in HTML from backend data

I recently worked on a project using express handlebars, where I was fetching data from the YouTube API. However, the titles of the data contained special characters such as '# (the ' symbol) and & (the & symbol). When attempting to render the ...

Nuxt.js Development Script Fumbles

Recently, I've been working on a website using Nuxt.js and have been really enjoying the process. However, I'm encountering an error that's puzzling me whenever I attempt to run $npm run dev: 0 info it worked if it ends with ok 1 verbose cl ...

What steps should I take to address and resolve this problem with my Angular $scope?

One of my partials utilizes a single controller named CaseNotesCtrl. However, I am encountering difficulties accessing $scope variables within this partial. Below is the code snippet: <div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotes ...