$window.location.Reload()

Asked

Viewed 925 times

2

I use Angularjs in a webapp, in this webapp I have implanted a map showing my clients from a marker. The map I’m using is Leaflet (http://leafletjs.com/) with a directive for Angularjs (https://github.com/tombatossals/angular-leaflet-directive).

My problem is this, when I first access the map, it works normally, when I change the route, it erases all the markers, going back to the map screen, it loads without the markers and they are shown only when I reload the page.

Function $window.location.Reload().

So I had the idea to use $window.location.Reload() when accessing the page where the map is. I call the function when I click on the menu icon (shortcut) of the page referring to the map and the page is reloaded showing the markers again.

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

View: This is the code that loads 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.buscaEnderecoClientesEmpresas()" markers="vm.markers" width="100%" height="480px"></leaflet>
    </div>
</div>

Controller: In the controller is the function used to load the BD data and assign to the markers. It is also in this function that I create the markers, extend the properties of the map, how to tell him that his initial position is in such a coordinate..

Consideration of the controller.

vm variable, receives $Scope.

var vm = $Scope.

        vm.markers = new Array(); //CRIA MARKERS A SEREM UTILIZADOS NO MAP

    vm.buscaEnderecoClientesEmpresas = function() { //Função utilizada para carregar os dados do BD e atribuir aos marcadores. Também é nesta função que crio os marcadores....
        vm.items = loadSaas(Cookies.get('crm_o2_hash')); // carregar saas id
        vm.items.then(function(items) { // ler array de retorno
            vm.saasid = items; //Armazena ID (saasid). 
            var dados = { 
                'saasid': vm.saasid
            }
            relatoriosService.carregarEnderecoClientesEmpresas(dados).then(function(response) {
                if (response.data != 'null') {
                    vm.enderecoClientesEmpresas = response.data; //ARRAY QUE VEM DO BD
                    angular.forEach(vm.enderecoClientesEmpresas, function(value, key) { //FOREACH UTILIZADO PARA PERCORRER ARRAY

                        vm.markers.push({
                            group: value.estado, //DADOS PROVENIENTES DO BD. 
                            lat: value.latitude, //DADOS PROVENIENTES DO BD. 
                            lng: value.longitude, //DADOS PROVENIENTES DO BD. 
                            message: "teste",
                            icon: {
                                type: 'awesomeMarker',
                                prefix: 'fa',
                                icon: icon,
                                markerColor: color
                            },
                            label: {
                                options: {
                                    noHide: true
                                }
                            }
                        });
                    });
                } else {
                    vm.enderecoClientesEmpresas = '';
                }

            }, function(error) {
                console.log('Erro findSemEmail: ', error);
            });
        });
    }


    angular.extend(vm, { // ESTENDE AS PROPRIEDADES DO MAP (MARCADORES, LOCALIZAÇÃO INCIAL..)
        center: { // LOCALIZAÇÃO INICIAL  .
            lat: -27.952419,
            lng: -52.211667,
            zoom: 6
        },
        defaults: { //LAYER É O TIPO DE MAPA A SER UTILIZADO
            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>',
            },
        }
    });

My problem is this, when the user, instead of using the system shortcuts to navigate, use the back arrow of the browser, the page will not reload, there is a way to make the page reload if it uses it in this way?

Or maybe when accessing a specific route reload the page.

CONSOLE PRINT’S:

Initial map status. With all markers loaded you can see that the array has been traversed 27 times (leafletDirective.layeradd). inserir a descrição da imagem aqui

In the image below is the return of the console when the route changes. See that the layers (markers, Tiles...) are removed. inserir a descrição da imagem aqui

And finally, in this image a layer (I believe it is the Tile (image of a map, in this case the Openstreetmap) is loaded, but not the rest of the layers that would be the markers (27)). inserir a descrição da imagem aqui

2 answers

3


After much research with Fred on chat we were able to conclude that this is a bug of the angular-leaflet-Directive directive

The problem is described in this report: https://github.com/tombatossals/angular-leaflet-directive/issues/381#issuecomment-46232650

Clusters are not redesigned because the group name is already defined when returning to the map

https://github.com/tombatossals/angular-leaflet-directive/blob/master/dist/angular-leaflet-directive.js#L2405

To resolve this you need to reset the variable groups of the Directive with the resetCurrentGroups which is available on leafletMarkersHelpers every time you navigate off the map, that is, every time $Scope is destroyed.

$scope.$on('$destroy', function () { 
    leafletMarkersHelpers.resetCurrentGroups(); 
});

This helper leafletMarkersHelpers needs to be injected into the controller before being invoked

  • 1

    Link to chat: http://chat.stackexchange.com/rooms/51887/discussion-between-fred-and-rodrigo-nishino Thanks Rodrigo!

3

You are using angular1?

It looks like the element is being initialized for the first time with ng-init and when the route changes the controller

You have considered porting these values that are being passed by ng-init to be provided by the route-related controller?

$routeProvider.when("/mapa", {templateUrl : "main.htm", controller: "MapaCtrl"})

app.controller("MapaCtrl", function ($scope) {

    $scope.buscaEnderecoClientesEmpresas = function(){ ... codigo aqui... }

    $scope.buscaEnderecoClientesEmpresas()

});
  • 1

    Thank you for answering! Yes, it’s Angular1. When you say the values, do you mean the values that are assigned to the markers? Like this for example: lat: value.latitude, //BD DATA.

  • 1

    vm.markers is an empty array that is populated somentewhen ng-init is invoked, only it is invoked only in the beginning.

  • When I change the route the search methodEnderecoClientesEmpresas is executed. However, the array is not updated. I ended up creating a function to create the array vm.markers and run this function every time the method is traversed, but it didn’t work. I’ll add some console prints to the question, maybe it’ll help.

  • Ahh, I tried to run the function on the controller yes, until I removed ng-init and left only on the controller, as shown in your code above. But it carries the same.

  • 1

    And this vm.items.then(Function(items looks like a solved Promise Sera that loses the reference?

  • This vm.items is used to load a user ID, so that it only shows information about this user. I edited the code. I had deleted prq I didn’t think it was necessary, but now it’s edited.

  • 1

    Is this vm.markers in the scope of the controller? It wouldn’t have to be $Scope.vm.markers ?

  • Ahh, I forgot to mention, the vm variable gets $Scope. So consider where you have vm. is $Scope.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.