What is the process for setting up the Google Maps API within an Angular application without relying on any directives

Currently, I am attempting to integrate Google Maps into the application that I am developing. Utilizing the Places API for certain functionalities has been successful thus far. However, I have encountered an issue when trying to display a map on a specific page - the map simply does not show up. Interestingly, there are no error messages presented in the console even when executing the following code.

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places"></script>

mapview.html

<div ng-controller="MapViewController as mapctrl" ng-init="initialize()">
<div class="container">

  <div class="row">

    <div id="map"></div>

  </div>

  <div ui-view></div>
</div>
</div>

mapViewController.js

(function(angular) {
    angular.module('myapp').controller('MapViewController', ['$state','$http','$stateParams','$window','$route','$document','$localStorage','$scope','$location', function($state,$http,$stateParams,$window,$route,$document,$localStorage,$scope,$location) {

      $scope.initialize = function(){
        console.log("log");
          var mapOptions = {
              zoom: 11,
              center: {lat: -34.397, lng: 150.644},
              mapTypeId: google.maps.MapTypeId.ROADMAP
          };

          var map = new google.maps.Map(document.getElementById('map'), mapOptions);
       };

      }]);
      })(angular)

Although the log message is displayed upon controller initialization, the map fails to appear on the page. If possible, I would like to resolve this issue without resorting to using any directives. Any guidance on achieving this would be greatly appreciated.

Answer №1

Ensure that you set the ng-app attribute in your HTML:

<html ng-app="mapApp">
 . . .
  <body ng-controller="MapController" ng-init="initMap()">
    <div id="map"></div>
  </body>
</html>

Next, correctly initialize your map using JavaScript:

angular.module('mapApp', []);

angular
  .module('mapApp')
  .controller('MapController', MapController);

  function MapController($scope){

    $scope.initMap = function() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 3,
            center: new google.maps.LatLng(32.483, 16.084)
        });
    }

}

Add a specified height and width to your element ID:

#map{
      height: 400px;
      width:  700px;
      border: 2px solid red;
 }

Take a look at this Plunker example I created which initializes a map without a directive.

I hope this information proves valuable.

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

Issue with Ajax request not redirecting to correct URL

I have been successfully using ajax requests in my document without any issues. I am looking to retrieve the user's coordinates as they load the document and then pass this data on to other methods for distance calculations. On the loading of the ind ...

Discovering unutilized node modules in your React project - A practical guide

Looking for a way to clean up unnecessary node modules and their dependencies from a project. I've done some research online and came across a few NPM packages that claim to achieve this, but none seem to meet my specific needs. Important: Node modu ...

Strategies for Ensuring Ember JS Waits for Asynchronous Functions to Respond Prior to Rendering

Currently, I'm tackling a project that came to the company through an outsourced channel. My query concerns the rendering of an image src. In the past, images were served from the filesystem. However, we've now transitioned to using AWS S3 bucke ...

encountering problems with Next.js routing resulting in 404 errors

I developed a Next Js 14 app where I had to change the routing names inside the pages before going live. For example, instead of 'Charts', I changed it to 'charts' and made similar modifications to other pages as well. However, after de ...

Does the require function in nodejs have any connection to the package.json file?

If 'random_module' is included in the list of dependencies in my package.json file, can I use the code var rm = require("random_module"); to access it? Essentially, does the argument for require function apply to any module listed under the depen ...

Upload an image converted to `toDataURL` to the server

I've been attempting to integrate the signature_pad library, found at signature_pad, but I am struggling to grasp its functionality. Can someone guide me on how to retrieve an image value and send it to my server? Edit: I have experimented with dec ...

The 'otherwise' controller in AngularJS does not execute when the resolution in another controller has not been successful

Imagine having routes set up in the configuration: $routeProvider .when('/person/:person_id', { controller: 'person', templateUrl: 'partials/person.html', resolve: { data: ['api', '$route', ...

Vue components fail to display properly when transitioning between routes in Vue (version 3) using the Vue Router

Just diving into VueJS version 3 and vue-router. Despite my efforts to troubleshoot by consulting Stack Overflow and Google, the issue remains unresolved. I have defined two routes: /login /admin/index The Problem: While the login route ...

Triggering a gTag Event on the Fly using Google Tag Manager

I implemented a script that triggers a dynamic gTag.js AdWords conversion based on various user interactions on my webpage. Everything was working smoothly until I switched to Google Tag Manager. Now, the code snippet: gtag('event', 'convers ...

Utilizing Puppeteer to Navigate and Interact with Elements Sharing Identical Class Names

I am new to Puppeteer and NodeJs, and I am attempting to scrape a specific website with multiple posts that contain a List element. Clicking on the List element loads the comment section. My question is: I want to click on all the list elements (since th ...

Why isn't the connect.use() function working in Node.js?

I have been studying and applying examples from a book to learn Node.js. While replicating one of the examples, which involved creating a middleware, I encountered an error when trying to run the JavaScript file. The error message stated "undefined is not ...

A guide on how to use Jasmine to mock $window.innerWidth in AngularJS

Within my AngularJS (1.4.4) application, there exists a factory: ( function () { "use strict"; angular .module("app") .factory("DeviceTypeService", DeviceTypeService); function DeviceTypeService($window) { functi ...

Navigating a Multi-Page Website with Sleek Scrolling

I've been searching for a solution everywhere but haven't had any luck. I'm trying to implement a smooth scroll effect that works seamlessly across multiple pages. For instance, the smooth scroll effect is present on the homepage with naviga ...

Nextjs - resolving the issue of shopping carts displaying incorrect total amounts

I am currently facing an issue with the total cart amount while building a shopping cart. The problem arises when I visit the cart page as it only displays the amount of the last item added to the cart. state = { cart: { items: [], total: 0 }, }; ad ...

Is it possible to manually input values when printing a PDF instead of pulling them from the main HTML?

I am facing a challenge in adding a "Print PDF" option to my website because it is built using Ext.js, and therefore the code is not in HTML. Despite searching for ways to print a PDF from the site, all solutions I found involve using HTML. Is there any li ...

Encountering an issue with my code in CodeIgniter

I encountered an error when trying to make an AJAX request in CodeIgniter, unlike the usual process in core PHP where we specify the file URL containing the query. The error I received was net::ERR_SSL_PROTOCOL_ERROR . Here is the JavaScript AJAX code sni ...

Can't access innerText in Firefox

This is the code snippet I'm having trouble with: <div id="code">My program<br />It is here!</div> <script type="text/javascript"> var program=document.getElementById('code'); ShowLMCButton(program.innerText); </s ...

Transfer sound data blob to server and store it as a file

Currently, I have 3 buttons on my webpage - one to start recording audio, one to stop the recording, and one to play the recorded audio. Using MediaRecorder makes it easy to capture audio as a blob data. However, I am facing issues when trying to upload th ...

How can I utilize a service for monitoring user data and ensuring that $watch() functions properly?

I'm a beginner when it comes to AngularJS and currently working on building a website that has a navigation bar dependent on the user's login status. My approach involves using a state model design with the Nav controller as the parent state for ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...