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

Can multiple groupings of objects be viewed in a JSON file?

Currently, I am interested in creating a leveling system without relying on a database. While I understand that using a database is the more efficient approach, my server doesn't have a large user base and I have yet to learn how to work with database ...

Boost Page Speed with Angular

Currently, I am working on a project using Angular and encountered an issue with testing the page speed on GTmetrix. Despite generating the build with the command ng build --prod--aot, the file size is 1.9mb, leading to a low speed in GTmetrix's analy ...

Is there a more efficient method for streamlining the Express-Validator middleware in a separate file

In my current project, there is a lot of validation required using Express-Validator. In each file, I find myself repeating the same validation code: //Validation and Sanitizing Rules const validationRules = [ param('tab').isString().isLength({ ...

Accessing the current clicked item in $scope using an Angular Directive within ng-repeat

I have set up a custom directive called calendar which includes a date picker created in JQuery. To associate the ng-model with the date picker, I am using the following code successfully: var clickedID = "#" + $scope.indexid + "_datePicker"; $(clickedID ...

`Easily handle a Restangular resource``

I'm struggling with using Restangular for the first time and I'm having trouble understanding how to handle promises within my own service. I've attempted to use the customGET method but in my controller, the response is an object containing ...

tips for selecting various API requests based on the selected drop down menu choice

Hey there! I'm looking to enhance my login page by adding a feature that allows users to select from a dropdown menu with different options. Each option will be linked to a specific API, and based on the API response, the user's ability to log in ...

ReactJS encountered an error: _this3.onDismissID is not defined as a function

My goal is to retrieve the latest news related to a specific search term from a website, showcase them, and provide a dismiss button next to each news item for users to easily remove them if desired. Here's a snippet of the code I'm using: import ...

In a Vue.js application, parameter passing does not function as intended

As someone who is new to JavaScript, I have a question regarding Vuex and creating a simple Todo Manager. I am facing an issue with deleting todos from my list and not getting the desired parameter (the id of the todo) in my actions. Here is the code snip ...

Modifying an element's value according to user input: Step-by-step guide

Within my dropdown menu, there is a single option labeled "Others". Upon selecting this option, a textbox appears allowing me to input custom text. Is it possible to dynamically update the value of the <option value="Others">Others</option>, ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

What causes the difference in behavior of nodejs function arguments when explicitly called?

As I refactor my nodejs application to improve code readability, I encountered an issue when calling a function directly. The following code works perfectly: router.route('/').get(({ query }, res, next) => { ItemsLogic.getItems(query) .the ...

Jquery's intermittent firing of .ajax within if statement

So, I've inherited a rather messy codebase that I need to modernize. The task involves upgrading from an old version of prototype to the latest jQuery 3.2.1 within a dated website built on php and smarty templates (not exactly my favorite). When a lo ...

history.push() function is ineffective within a JavaScript file that does not contain a class

I've been delving into React and encountering an issue with the history.push("/dashboard") method, it's not functioning as expected. import axios from "axios"; import { GET_ERRORS, GET_PROJECT, GET_PROJECTS } from "./types"; export const createP ...

Using AngularJS directive within an HTML input tag is simple and straightforward

<input type="text" no-special-char class="form-control" name="name" placeholder="" required="required" value="" ng-model="Name" required no-spl-char-name /> Is this the proper method? ...

Enable a click event within an iFrame by clicking on an element in the parent document

I am attempting to trigger the click event of an element inside an iFrame (specifically a standard Twitter follow button) when clicking on an element within my main webpage. Below is the code snippet I have been experimenting with, but unfortunately it do ...

Clicking will cause my background content to blur

Is there a way to implement a menu button that, when clicked, reveals a menu with blurred content in the background? And when clicked again, the content returns to normal? Here's the current HTML structure: <div class="menu"> <div class=" ...

Is there a way to prevent a page from automatically redirecting to another page without relying on user action or using the StopPropagation and window.onbeforeunload event?

function confirmExit(e) { var f = FormChanges(); //checking if the page has been modified if (f.length > 0){ if (submitForm == false) { if(!e) var e = window.event; e.cancelBubble = true; e.returnValue = "You ...

"Encountering difficulty in retrieving information from $q and integrating it into the

I am facing an issue with binding data from an API to my scope using promises in AngularJS. Despite successfully retrieving the JSON data from the server, the $scope variable remains empty. Any assistance on this matter would be greatly appreciated. Thank ...

Using Google Tag Manager to track the values of a formula field

I am looking to track the selected destination in a form using Google Tag Manager. To achieve this, I have created a custom JavaScript variable: function() { var inputField = document.getElementById("country"); return inputField.value || ""; } When ...

Discovering the geographical location of all users using Node.js: A step-by-step guide

My current task involves determining the geoip location of users. I have implemented a code that stores the user's address in the database and then displays the geoip location accordingly. However, if a user changes their location and logs in from a d ...