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

Can JavaScript be used to continuously monitor a window variable object in real-time?

Is there a way to dynamically control a variable in JavaScript? I'm currently working on a code that needs to display a button when it reaches the last signature of an automatic request process. The code for activating/deactivating the button is show ...

What is the best way to send $event data from a custom directive to a function?

Here is a directive I created to detect the enter key being pressed: .directive('enterSubmit', function() { return { restrict: 'A', link: function(scope, elem, attrs) { elem.bind('keydown', function(event) { ...

Are there any publicly accessible Content Delivery Networks that offer hosting for JSON2?

Everyone knows that popular tech giants like Google and Microsoft provide hosting for various javascript libraries on their CDNs (content distribution networks). However, one library missing from their collection is JSON2.js. Although I could upload JSON2 ...

Having trouble getting the form to submit using AJAX

=====ANOTHER UPDATE==== (if anyone is interested!) The previous solution I shared suddenly stopped working for some reason. I added a beforeSend function to my ajax request and inserted the section of my JavaScript code that validates my form into it. It&a ...

Unable to retrieve the JSON response sent by the REST API within an HTML page

My ajax function is unable to properly receive the JSON content generated by a REST API. The REST API successfully creates the JSON data, but when passed to my ajax function, it does not work as expected. function loadJsonData(){ var dropDownValue = ...

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

The declaration file for module 'react-scroll-to-bottom' appears to be missing

I recently added react-scroll-to-bottom to my project and it is listed in my dependencies. However, I am encountering the following error: Could not find a declaration file for module 'react-scroll-to-bottom'. The path 'c:/Users/J/Desktop/w ...

Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value: <div v-for="group in groups"> <input type="checkbox" v-model="selected" :value="group"> <template v-for="item in group"> <input type ...

Postpone the appearance of a pop-up message, make it show up only once

Is it feasible to create a pop up that appears after 4 seconds and stays visible until the user interacts with the mouse? The pop up should not appear if the user scrolls before it shows. You can refer to the image for more details on the pop up box :) &l ...

Error message: Unable to access the state property of an undefined object

I've been attempting to integrate a react sticky header into my stepper component. However, I've encountered an issue where it doesn't render when added inside my App.js file. As a result, I've started debugging the code within App.js ...

Ajax successful event fails to trigger

Having Trouble Implementing Okta Authentication with WebForms The login functionality is working, but the redirect part is not functioning correctly I have attempted to use void and return a JSON object/string, but it does not seem to work If I remove th ...

Vue.js enhances user input interactions

CSS <span :style="{ display : displayTitle }" @click="toggleInput()"> {{ text }} </span> <input v-if="isEditing" type="text" v-model="text" @blur="hideInput" @keydown.enter="saveChanges" @keydown.esc="cancelE ...

Learn how to automatically populate input fields based on the values entered in previous fields. These dynamic fields are generated based on the user

In the following code snippet, fields are dynamically created using jQuery... For more visual explanation, refer to this image: The goal is to calculate the grand total based on previous inputs and display the result when an onclick() event occurs. < ...

Are Viewmodel contents empty after ajax request?

Currently working on an ASP.NET MVC application, I am in the process of developing a search page that showcases both the search box and the table of results simultaneously. To achieve this functionality, I have utilized Partial Views along with AJAX/JSON c ...

Guide on how to retrieve a single document (mongoose/mongoDB)

Storing data in a database is crucial for many applications. { "_id": "62fa5aa25778ec97bc6ee231", "user": "62f0eb5ebebd0f236abcaf9d", "name": "Marketing Plan", "columns": [ { ...

There was an error that was not properly handled: The property 'Minus' cannot be read because it is undefined

I tried uninstalling and reinstalling NPM using the command npm install but encountered an error afterwards. I also attempted npm audit fix --force which resulted in the following error: An unhandled exception occurred: Cannot read property 'Minus&a ...

Modify the div's background color specifically with AngularJS

After creating a list using divs, my goal is to modify only the background color of the selected div when a user makes a choice from the list. I have accomplished this by defining two distinct CSS classes with the main difference being the background colo ...

The function of removing the ng-submitted class in AngularJS after form submission seems to be malfunctioning when using setPristine and setUnt

When a form is submitted in Angular, the class ng-submitted is automatically added by default. In my attempts to reset the form state by using $setPrestine and $setUntouched, I encountered some errors that prevented it from working properly. Examples of t ...

Using dangerouslySetInnerHTML in React within a Fragment

In my current project, I have a specific requirement where I need to format text in React and also include HTML rendering. Here's an example of what I'm trying to accomplish: import React, {Fragment} from "react"; import {renderToString} from " ...

Guide on using jQuery to incrementally cycle through an array using a button

I am facing an issue with iterating through an array of objects using a button. The iteration is skipping 2 on each click instead of moving to the very next record. Can someone help me troubleshoot this problem? Or suggest a better approach to iterate thro ...