Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object:

leafletData.getMap().then(function(map)
{
    map.invalidateSize();
    map._onResize();
});

Encountering a minor yet bothersome problem with the Leaflet directive for AngularJS (https://github.com/angular-ui/ui-leaflet) and Google Maps plugin (https://github.com/shramov/leaflet-plugins).

At times, markers load fine but the map fails to display. A simple page refresh resolves it temporarily...

Screenshots provided below (captured on mobile but issue persists across desktop browsers):

https://i.stack.imgur.com/nONjB.png

Occasionally the map loads eventually but without proper bounds set:

https://i.stack.imgur.com/OGeOG.png

Desired appearance (achieved most of the time):

https://i.stack.imgur.com/rXmnk.png

Template:

<div class="stations-map" ng-controller="mapCtrl" ng-show="mapObj.visible">
        <leaflet layers="mapObj.layers" lf-center="mapObj.center" bounds="mapObj.bounds" markers="mapObj.markers" height="480px" width="100%"></leaflet>
    </div>

Controller:

app.controller("mapCtrl", ['$scope', '$filter', 'propertyService', 'groupService', 'leafletBoundsHelpers', function ($scope, $filter, propertyService, groupService, leafletBoundsHelpers){
var properties = null;

var mapObj = {

    center: {},
    bounds: [],
    markers: {},

    layers: {

        baselayers:
        {
            googleRoadmap: {name: 'Google Streets', layerType: 'ROADMAP', type: 'google'}
        }

    },

    visible: false

};

...

$scope.$on('data-switched', function()
{
    resetMapAndHide();
    $scope.mapObj = mapObj;
});}]);

Appreciate any advice or pointers! Thank you.

Answer №1

When encountering issues with Google Maps, I found that a resizing problem was at the root of it. By triggering a Resize event, I was able to successfully resolve the issue. Perhaps this approach could help you as well.

$scope.initializeMaps = function(test){
            if(test.gps){
                var arrLatLng = test.gps.split(',');
                var latlng = new google.maps.LatLng(arrLatLng[0], arrLatLng[1]);
            } else {
                var latlng = new google.maps.LatLng(37.42224,-122.0883822);
            }

            var myOptions = {
                zoom: 9,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map"),
                myOptions);

            var input = document.getElementById('maps-input');
            var searchBox = new google.maps.places.SearchBox(input);

            map.addListener('click', function (e) {
                placeMarker(e.latLng, map, test);
            });

            map.addListener('bounds_changed', function () {
                searchBox.setBounds(map.getBounds());

            });

            // TRIGGER RESIZE EVENT TO RENDER MAP
            $timeout(function(){
                google.maps.event.trigger(map, 'resize');
                if (marker && test.marker) {
                    map.setCenter(marker.getPosition());
                }
            },1);

        };
        
        var marker;

        function placeMarker(location, map, test) {
            $scope.$apply(function () {
                test.gps = location.lat() + "," + location.lng();

            });

            if (marker && test.marker) {
                marker.setPosition(location);

            } else {
                marker = new google.maps.Marker({
                    position: location,
                    map: map
                });
            }
            test.marker = true;
        };

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

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

Retrieving a single item from an array of objects with the help of body parser

I need assistance with sending an array of objects to a post route in my express app. Here is my form (written in ejs format): <form action="/archiveList/<%= list._id %>" method="POST"> <input type="hidden" name="list" value = <%= items ...

Substitute the Iframe element with Ajax technology

Currently, I am working on a project where I want to include previews of various websites within my own website. Right now, I am using Iframes to load the website previews and allow users to interact with them. For SEO purposes, I have decided to replace ...

The functionality of the Bootstrap dropdown list button is not functioning properly on mobile devices

Currently, I am in the process of developing a website and testing its mobile view on my iPhone. The website is still using bootstrap 3, but I have encountered some issues. When I tap on the navigation button on my iPhone, nothing happens - no dropdown lis ...

AngularJS is causing the D3.js Bubble chart graph to not display properly

I've been attempting to enhance my Bubble chart graph created with D3.js by incorporating AngularJS, but I'm facing some difficulties. Despite going through this tutorial, nothing seems to be working as expected. Below is the code I have written ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

What are the best practices for storing an array of objects in MongoDB with Mongoose?

For my project, I needed to store data in a mongoDB document as an array of objects using Javascript, Node JS, Express framework, and Mongoose library. After researching online, I found two different methods to achieve this: Creating another sub-schema ...

Creating a Slider with a Multitude of Images

I am working on a project to develop a gallery that pulls images from a JSON source. I have successfully implemented infinite scrolling to display the images on the first page. However, I am now facing a challenge when it comes to showing the selected imag ...

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

Is there a way to turn off the auto-complete feature for JavaScript keywords in HTML within JSX in WebStorm?

While using WebStorm, I've noticed that it automatically completes JavaScript keywords as I type regular text in JSX. This behavior is starting to frustrate me because I have to constantly press ESC or click elsewhere to hide the auto-complete popup. ...

Is there a way to print the full page including scroll tab content?

I am facing an issue where I want to print the entire page including the scrollable content within a tab. Currently, only the visible screen content is being printed. ...

Warning: An unhandled promise error occurred due to a validation error

I've been facing an issue for the past few days. Currently, I'm diving into learning the MEAN stack, but while trying to create a user on MongoDB using Mongoose schema, I encountered this problem: (node:93337) UnhandledPromiseRejectionWarning: ...

Adjust the color of the button and update the text using AngularJS

i have been attempting repeatedly, but to no avail. Here is my button: <div ng-class="User.active? 'btn btn-danger' : 'btn btn-success' " ng-click="User.active=!User.active"> {{ User.active ? 'Desactive' : &apo ...

How can the plus icon on the left side of an expandable row in Angular UI-Grid be moved to the right side?

I am currently utilizing the expandrow feature in ui-grid, as seen in this demo from the official ui-grid site. Due to my language being RTL (right-to-left), the plus icon is appearing on the right-hand side. For architectural reasons, I require the plus ...

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...

Creating a toggle feature using ng-switch

I'm having trouble getting this code to function correctly as a toggle. Can anyone offer any suggestions on what might be causing the issue? <div ng-switch="!!myvar"> <a ng-switch-when="false" ng-click="myvar = true" style="cursor:poin ...

One click wonder: Easily print any webpage content with just the click of a button!

For example, upon clicking the button on my webpage, I want the content of another page to be sent directly to a printer. The objective is to bypass the print dialog box and print preview that typically appears when using the browser's default printin ...

Guide on how to dynamically add AJAX JSON array response to an HTML table

Hey! I need some advice on how to dynamically append a JSON Array response to an HTML table after submitting a form using AJAX. Here's the scenario: This is my form : <form id="myForm" method="POST"> <input type=" ...

Tips on how to update a table following each button click during an ajax request

I am encountering an issue while trying to display data in a table by clicking on a search button. The problem arises when there is no data between the specified "Fromdate - Todate" range; the error message appears correctly. However, even after entering t ...

Is there a way to confirm that a file has been chosen for uploading prior to form submission, by utilizing the jquery validator?

I have a section on my website where users can upload files. I am trying to implement validation to ensure that a file has been selected before the form is submitted. Currently, I am using the jQuery form validator plugin for handling form validations. Th ...