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

Sinon causing 'unsafe-eval' error in Chrome extension unit tests

Recently, I've been conducting unit tests on my Chrome extension using Mocha, Chai, and Sinon. However, I encountered an issue when attempting to stub an object from a method: EvalError: Refused to evaluate a string as JavaScript because 'unsafe ...

What is the best way to include the Mailchimp integration script in the `Head` of a Next.js project without causing any pre

Hello there Incorporating mailchimp integration into my nextjs site is proving to be a challenge. I've been attempting to add the following code snippet to next/Head within my custom _document <script id="mcjs">!function(c,h,i,m,p){m= ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

retrieve data from JSON file

function retrieveDataFromProfiles(){ const fs = require('fs') fs.readFile('src/data/profileInfo.json', function(error, data){ if(error){ alert(error); } var profileData = JSON.parse(data); //retrieves the JSON data of ...

The functionality to deselect multiple options in a select box is not functioning properly

There seems to be an issue with removing the selected attribute from the selected values in a jQuery multiselect box. The console is not showing any errors. You can view a working example here The problem lies in this code snippet: $("#mltyslct option ...

Basic PHP code converted into a JavaScript function for an onSubmit event within an HTML form

I have been trying to figure this out for hours. The goal is to submit a form only if one of the inputs matches a PHP echo. To simplify the script, it looks something like this: <head> </head> <body> <?php $A = rand(0,10); $B = r ...

Samsung S4 Android device experiencing interruption in HTML5 video playback

When using Android Webview to play html5 videos, including Youtube videos (using my own tags and Youtube embedded iFrames), I came across an issue with the Samsung Galaxy S4. The problem occurs in the following scenario: Play a video. Press 'back&ap ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...

Select Menu (Code Languages:CSS, JS, HTML, BBCode)

I'm currently in the process of setting up a BB code for a forum I moderate. Here's the code snippet I'm using to generate a dropdown box that users can add to the signature field of their profiles: <!DOCTYPE html> <html> <d ...

Comparing front end automation between JavaScript and Java or Ruby

Could you provide some insights on why utilizing a JS framework like webdriverio is preferred for front end automation over using Selenium with popular languages like Java or Ruby? I understand that webdriverio and JS employ an asynchronous approach to fr ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

Unable to alter Mui input label color upon focus using theme.ts

In my next.js app, I'm facing an issue with changing the color of the label in a Material UI input field using Mui. Despite updating the theme.ts file to change the border bottom color and label color, only the border bottom color is being applied. T ...

Updating Button Color Based on Input Field Value in EJS

How can I change the color of a button in EJS when the input value changes? <div> <textarea name="mytextarea" id="inputcontent" cols="30" rows="3" style="margin-top: 10px; margin-bottom: 10px; f ...

Using gmaps4rails: A guide on extracting JSON data from the controller

I have a model named shop and I want to create a simple alert box using JavaScript that shows the name of the shop when a marker on the map is clicked. Here's my code: # controller @json = Shop.all.to_gmaps4rails do |shop, marker| marker.json({ id ...

Guide on populating a series of rectangles in a line based on values stored in an array using d3.js

I have 100 rectangles arranged in a 10x10 square. My goal is to assign colors to the rectangles based on values from an array var avg = [1, 4, 4, 7, 11, 15, 58] I'm facing an issue at the value 4 being repeated and I find the current code quite mess ...

Error message "Encountered an unknown type 'ForOfStatement' when attempting to execute an npm library"

Currently, I am in the process of integrating the PhotoEditor SDK library into my Ruby on Rails project. To achieve this, I have been meticulously following the installation guidelines provided in the official documentation. However, during the setup proce ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Error: The document object is not defined when attempting to access it within a

<script type="module" src="/scripts/navbar.js"></script> <script> async function fetchContent(e) { e && e.preventDefault(); const response = await fetch('https: ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

Mastering the art of elegantly parsing the 'address_components' in Google API using Python

Can you help me troubleshoot my code? I'm trying to fetch JSON data from the Google API. Although I am aware of this approach, I prefer to validate the JSON and extract the street information using if i['types'] == 'street_number&apos ...