The functionalities of Google Maps are experiencing issues within AngularJS when utilizing the $route feature

Having Issues with Google Maps in AngularJS when using <ng-view></ng-view>

Routing Configuration

app.config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/', {
      templateUrl: 'home.html',
      controller: 'homeController'
    })
    .when('/contact', {
      templateUrl: 'contact.html',
      controller: 'contactController'
    })
    .otherwise({
      redirectTo: '/'
    });
});

Initializing the Map

<div ng-controller="contactController" ng-init="loadScript()">
    <div id="my-map" ng-init="initialize()"></div>
</div>
app.controller('contactController', function($scope, $http){
    $scope.loadScript = function () {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyDtwLGMk2mRH8pFkhJrRtJ0lTyT0PokK4Q&sensor=false&callback=initialize";
        document.body.appendChild(script);
    };
    $scope.initialize = function () {
      console.log("the map initialization works now");
        var myLatlng = new google.maps.LatLng(51.5120, -0.12);
        var mapOptions = {
            zoom: 14,
            center: myLatlng,
            disableDefaultUI: false,
            mapTypeControl: false,
            disableDoubleClickZoom: true,
            scrollwheel: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            styles: [{
                stylers: [{
                    hue: "#E16D65"
                }, {
                    saturation: -40
                }]
                }, {
                    elementType: "geometry",
                    stylers: [{
                        lightness: 0
                    }, {
                        visibility: "simplified"
                    }]
                }, {
                  featureType: "landscape",
                    stylers: [{
                      lightness: 100
                    }]
                }, {
                        featureType: "road",
                        elementType: "labels",
                        stylers: [{
                            visibility: "off"
                        }]
                    },{
                      featureType: "road.arterial",
                      elementType: "geometry.fill",
                      stylers: [{
                        color: "#E16D65",
                      }]
                    },{
                      featureType: "road.local",
                      stylers: [
                        { color: "#ff8c86" },
                        { lightness: 75 }
                      ]
                    },{
                    featureType: "administrative.locality",
                    elementType: "labels.text",
                    stylers: [
                      { color: "#666666" },
                      { weight: 0.4 }
                    ]
                },{
                  featureType: "poi.park",
                  stylers: [
                        { lightness: 100 }
                  ]
                }
            ]};
        var map = new google.maps.Map(document.getElementById("my-map"), mapOptions);
        map.panBy(-100, 0);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map
        });
        google.maps.event.addDomListener(window, 'scroll', function () {
            var scrollY = $(window).scrollTop(),
                scroll = map.get('scroll');
            if (scroll) {
                map.panBy(0, -((scrollY - scroll.y) / 3));
            }
            map.set('scroll', {
                y: scrollY
            });
        });
        google.maps.event.addDomListener(window, "resize", function() {
            var center = map.getCenter();
            google.maps.event.trigger(map, "resize");
            map.setCenter(center);
        });
    };
});

Unfortunately, there is an issue displayed on the FirefoxDeveloperEdition console

Demo page

Answer №1

Dealing with a similar issue, I found a solution by implementing the following steps:

index.html:

<div ng-view=""></div>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=myKey"></script>

myMap.html:

<div class="fullmapContainer">
    <div id="fullmap-canvas"></div>
</div>
<script src="../scripts/custom/infos/google-maps/myDynamicMap.js"></script>

myMap.js:

angular.module('fullmap-canvas', [])
        .controller('FullmapController',[ 
                   $(document).ready(function (){

  var myCenter=new google.maps.LatLng(lat,lng);
  $(function initialize() {

  /*Code for beautiful map options*/

 function loadScript() {

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
  '&signed_in=true&callback=initialize';
  document.body.appendChild(script);
  }

  window.onload = loadScript;


  })]);

myMapController.js:

myApp.controller("FullmapController", ["$scope",function($scope){

 }]);

myRoutes.js:

myApp.config(function ($routeProvider) {
$routeProvider
.when('/myMap', {
      templateUrl: 'views/myMap.html',
      controller: 'FullmapController'
 })
  .otherwise({
     redirectTo: '/'
   });
})

Css:

#fullmap-canvas{height: 100%; width: 100%;}

I hope this information proves to be helpful in resolving your issue.

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

What is the best way to transfer a variable from a Node.js Express server to an EJS HTML file in order to toggle alert visibility?

Hello, I am currently facing a challenge in sending a variable from my app.js file to my ejs HTML file in order to toggle the display of an alert. Here is what the relevant part of my app.js code looks like: view image description here Initially, I attem ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Display a clean and simple toastr notification

Is there a way to specifically clear or hide just one toastr message when multiple messages are displayed, without clearing all of them at once? I've attempted the code below, but it didn't work for me. toastr.clear([toast]); For more informati ...

What are the steps for converting a structured text document into a SQL table?

I am currently working on a project that involves the need to save and load a structured text document, similar to MS Word, into/from a MySQL table. For instance, if given a sample document like sample.doc, the goal is to save both the content and formatt ...

PHP - Issue with AJAX Login Functionality

I have been developing an AJAX login system and encountering an issue where it does not send any response back unless I use exit("error here") in the script. However, my goal is to return a JSON response instead. The form structure: <div id="account" ...

Error message: The function r is not defined - Issue with Google Sign in on React app

I have successfully implemented Google Sign In for my react app during development, but I am facing an issue with it in the production environment. The npm module that I am using for Google authentication is available at https://www.npmjs.com/package/reac ...

What is the best way to use toggleClass on a specific element that has been extended

I have been experimenting with this code snippet for a while. The idea is that when I hover my mouse over the black box, a red box should appear. However, it doesn't seem to be working as expected. Could someone please review this script and let me k ...

The correct terminology for divs, spans, paragraphs, images, anchor tags, table rows, table data, unordered lists, list

Just wondering, I've noticed that every time I come across a page element '<###>[content]<###>' and want to learn how to manipulate it, I usually search for something like "how to do x with div" or "how to get y from div". I know ...

Creating a custom AngularJS filter to search within an array of objects

I'm currently working with an object in my project: {"A":[],"B":[],"C":[],"D":[],"E":[],"F":[{"name":"Fargo","id":29}],"G":[],"H":[],"I":[],"J":[],"K":[],"L":[],"M":[],"N":[],"O":[],"P":[],"Q":[],"R":[],"S":[{"name":"Sullivan","id":23},{"name":"Sven" ...

Do we require Node JS for developing Angular JS applications? If so, what is the rationale behind it? And why is Node JS not needed in a production environment?

Do you need Node.js to develop an AngularJS application? If so, what is the reason for that requirement? I have come across some articles stating that Node.js is necessary when building an AngularJS app, however, it is not needed in production. I am puzzl ...

Encountering an "Undefined index" error when attempting to send a file and path using FormData through

I have a question about my code. I am trying to send a file and a path to the server. The path needs to be constructed using these variables so that I can use it to output the file later on. var FD = new FormData(); var MyString = "uploads/docs/KEP" + m ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

Achieve seamless integration of PHP function execution with Javascript onClick without the need for page

After delving into my research, it seems like Ajax and/or JQuery may be the way to go for what I'm trying to achieve. However, I wanted to double-check before moving forward in that direction. The task at hand involves using a javascript onclick func ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...

Issue with FusionCharts rendering correctly arises when the <base> tag is present in the HTML head section

Combining AngularJS and FusionCharts in my web application has led to a unique issue. The upcoming release of AngularJS v1.3.0 will require the presence of a <base> tag in the HTML head to resolve all relative links, regardless of the app's loca ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...

Tips for maintaining previously accessed data when utilizing useQuery

I am currently working on incorporating a GET request using useQuery from the react-query library. Below is the relevant code snippet: import queryString from "query-string"; import { useRouter } from "next/router"; const { query } = ...

What is the best way to display the tabcontent when clicking on a menu tab in this code, as neither method seems to work?

Take a look at my JSFiddle demo: <http://jsfiddle.net/xrtk9enc/2/> I suspect that the issue lies within the javascript section. My html code includes an Unordered List that serves as the tab menu. Each href of the menu corresponds to a tab content, ...

Error encountered while sending AJAX request with JSON data type

Is it possible to submit a Form using ajax with the jsontype? Suppose I have 5 fields in the form, where 4 of them are normal textboxes and one field contains JSON. When trying to send this data via ajax, an error is thrown. How can I resolve this issue? ...

Issue with NullInjectorError: Failure to provide a custom component - Attempting to add to providers without success

I keep encountering errors during my test attempts... Despite looking into similar issues, I am still facing problems even after adding my custom LoginComponent to app.module.ts providers. It is already included in the imports section. app.module.ts @Ng ...