Refreshing the current window with the ``Window.location.reload()`` function

I have integrated a map that displays clients using markers. The map I am utilizing is Leaflet with an AngularJS directive.

The issue I am facing is that when I initially access the map, it functions correctly. However, when I change routes, all the markers disappear. Upon returning to the map screen, the markers do not show up until I reload the page.

Solution:

To address this problem, I implemented a function $window.location.reload() to reload the page whenever I access the page where the map is located. This function is triggered when clicking on the menu icon of the page associated with the map, effectively reloading the page and displaying the markers once again.

vm.reloadRoute = function (){
    $window.location.reload();
}

View: Here is the code snippet responsible for loading the map.

<div class="col-md-12 box_map" style="padding: 20px 30px 20px 30px;">
<div id="recent_activity" class="box_whiteframe_map">
    <leaflet defaults="vm.defaults" lf-center="vm.center" ng-init="vm.searchClientCompanyAddress()" markers="vm.markers" width="100%" height="480px"></leaflet>
</div>

Controller: Within the controller, you'll find the function used to fetch data from the database and assign it to the markers. It's also within this function that the markers are created and additional map properties are extended, defining its initial position.

vm.markers = new Array(); // Create markers to be used on the map

vm.searchClientCompanyAddress = function() { 
// Function used to load DB data and assign to markers...
    vm.items.then(function(items) {
        relatoriosService.loadClientCompanyAddress(data).then(function(response) {
            if (response.data !== 'null') {
                vm.clientCompanyAddresses = response.data;
                angular.forEach(vm.clientCompanyAddresses, function(value, key) {

                    vm.markers.push({
                        group: value.state,
                        lat: value.latitude,
                        lng: value.longitude,
                        message: "test",
                        icon: {
                            type: 'awesomeMarker',
                            prefix: 'fa',
                            icon: icon,
                            markerColor: color
                        },
                        label: {
                           options: {
                                noHide: true
                            }
                        }
                    });
                });
            } else {
                vm.clientCompanyAddresses = '';
            }

        }, function(error) {
            console.log('Error finding without Email: ', error);
        });
    });
}

angular.extend(vm, {
        center: {
            lat: -27.952419,
            lng: -52.211667,
            zoom: 6
        },
        defaults: {
            tileLayer: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
            zoomControlPosition: 'topright',
            tileLayerOptions: {
                opacity: 0.9,
                detectRetina: true,
                reuseTiles: true,
                attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> | &copy <a href="http://www.openstreetmap.org/copyright">Funil PRÓ</a>',
            },
        }
    });

Despite my solution, there remains an issue where navigating back using the browser arrow does not trigger a page reload. Is there a way to force a page reload in such instances?

Alternatively, is it possible to reload the page upon accessing a specific route?

Answer №1

"Maybe, we can consider reloading the page when accessing a specific route."

A way to achieve this is by utilizing the $routeChange event:

$rootScope.$on("$routeChangeStart", function(event, next, current) {
    var urlFrom = current.$$route.originalPath; // Previous page url
    var urlTo   = next.$$route.originalPath;    // Next page url
});

Do not forget to include $rootScope and $window in your module dependencies.

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

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

What is the best way to reset the values in react-multiple-datepicker?

Having trouble clearing values assigned in react-multiple-datepicker library. import MultipleDatePicker from "react-multiple-datepicker"; import React from "react"; class Addjob extends React.Component { constructor(props) { super ...

Adjust the form action and text input name according to the selected radio input

Seeking assistance with the following code, can someone help? $(document).ready(function() { $('#searchform').submit(function() { var action = ''; if($('.action_url').val() == 'l_catalog') { ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

Is there a way to automatically adjust the position of a tooltip div based on its location relative to the screen in AngularJS?

I've implemented AngularJs to create a grid with repeated li elements, each displaying a description box when hovered over. However, I am facing an issue where the description box goes off-screen when hovering over items on the right side of the grid. ...

Transferring information from a Jade file to a Node.js server

I'm currently working on creating a data object within my Jade view page that will be used in my server-side JS. The data object involves dynamic HTML generation that inserts input boxes based on user input. function addDetail() { var det ...

What is the best way to apply color to a line-through click event in React without affecting the font color?

I'm attempting to change the click event on a line-through element to turn red when clicked, but I can't find any solutions. I've tried various methods with no success. Edit: After adding "color":"red" following "none", the line is now red, ...

Arranging date and time in jQuery based on AM/PM notation

I have written some JavaScript code to sort dates in ascending order (from newest to oldest). I have successfully sorted the dates, but I am having trouble sorting the time with AM or PM using a 12-hour format. I can do it in a 24-hour format, but not in ...

Guide to generating an array entry for every line of a text file in node.js

Struggling with converting each line of a text file into an array entry in node.js The array I am working with is named "temp." The code below successfully prints out each line: var temp = []; const readline = require('readline'); const fs = re ...

The issue of an unsuccessful Ajax call arises in a WordPress plugin when utilizing wp_remote_get

Encountering difficulties with the wp_remote_get function in my Wordpress plugin. The objective is to invoke a method within my primary public class using ajax. However, every time I attempt to make the call with the wp_remote_get function, it fails. This ...

Should we define all public methods or prototype each method separately?

Typically, when I create a library, my approach is as follows: var myLibrary = (function() { return { publicProperty: 'test', publicMethod: function() { console.log('public function'); }, ...

What is the best way to send a message to multiple clients using different workers in both WebSocket and Express?

Currently in my express app, I am utilizing clusters and the ws package to run my project with a socket connection. The issue arises when a client connects to the socket - only one worker (such as worker with id 1) handles the connection. If another client ...

Leveraging Next.js 'useClient' in conjunction with server component (global)

Hello there! I'm trying to achieve a 50% opacity effect on my Gallery when the search bar is in use. However, I'm facing challenges using 'use client' with the glob library. Here's the code snippet: app/page.tsx "use client&qu ...

Exploring the intersection of JavaScript and PostgreSQL: Leveraging timezones and timestamps

I'm a bit confused about how to properly use timestamps. For example, when a user creates an article, they can choose a PublishDate, and the system also automatically stores a CreateDate. a. Should I make both PublishDate and CreateDate timestamps wi ...

What steps do I need to take in order to implement a basic ZeroClipboard copy-to-clipboard feature in jQuery on jsFiddle with just one click?

I'm having trouble implementing ZeroClipboard in a jQuery environment. My goal is to have the text within each div with the class copy copied when clicked. The following jsFiddle demonstrates the functionality with double click using the stable ZeroC ...

Trigger a jQuery function upon clicking a button

I am attempting to create a jQuery function that can be called independently, and then trigger the function when a click event occurs. Below is the code I have put together: HTML: <input type="text" class="form-control email_input" name='email&ap ...

Guide on incorporating a JS file in a React application

I recently obtained a template for my website that includes the following JS file which is being called from my React component. !(function($) { "use strict"; // Hero typed if ($('.typed').length) { var typed_strings = $(&quo ...

Utilizing JavaScript and jQuery to make a query to mySQL

Looking to solve a SQL database query challenge using JavaScript or jQuery? Here's the scenario: I have a SQL db and typically use the following query to retrieve data based on distance from specified coordinates: SELECT id, ( 3959 * acos( cos( rad ...

The creation of an indexedDB database and the addition of content encountered an error while trying to perform a 'transaction' on the IDBDatabase

I am relatively new to using IndexedDB and have successfully created a database. However, I am encountering an error when trying to add content to it. The specific error message reads: Uncaught NotFoundError: Failed to execute 'transaction' on ...