Error: Attempted to call $scope.map.control.getGMap function when clicking on the Map, but it is not defined

I'm currently working with Angular-Google-MAP and I'm trying to add a marker to the map. However, whenever I click on the map, I receive an error message saying

$scope.map.control.getGMap is not a function
. This error is occurring within the geocodePosition() function when the Map click event is triggered. Can someone please help me understand why this is happening?

<ui-gmap-google-map center='map.center' zoom='map.zoom' control='map.control' id="map-canvas" events="map.events">
   <ui-gmap-markers models="markers" idkey="markers.id" coords="'coords'"  events="markerEvents" icon="'icon'">                 
   </ui-gmap-markers>   
</ui-gmap-google-map>

In controller

function MapController($scope, GMapReady, GoogleMapApi, $timeout) {
     GMapReady.promise().then(
         var map={
             center: {
               latitude: 21.1458004,
               longitude: 79.08815460000005
             },
             bounds : {northeast : { latitude : 79.08815460000005, longitude : 79.08815460000005},
                       southwest : { latitude : 79.08815460000005, longitude : 79.08815460000005}},
             zoom: 5,
             control : {}
            }; 
            $scope.map=map;

            $scope.map.events ={
               click: function(map, eventName, originalEventArgs){

              var e=originalEventArgs[0];
              var lat=e.latLng.lat(),lon=e.latLng.lng();

              var latlng = new google.maps.LatLng(lat, lon);
              geocodePosition(latlng);                 
            }
        }// end of Map event
     );

    function geocodePosition(pos){
       .....some code .......
       ......................
     var map_obj=$scope.map.control.getGMap();
     var service = new google.maps.places.PlacesService(map_obj);  
    };
}

Answer №1

There seems to be a mistake in the provided example, where the then function requires a function callback as its first argument:

uiGmapIsReady.promise().then(function(maps) {
     var map = maps[0]; // obtain the first map instance 
});

The issue arises from:

$scope.map.control.getGMap is not a function

This occurs because $scope.map.control is only initialized after the map has finished loading.

Note: In the current version of the angular-google-maps library, use the uiGmapIsReady service to ensure directives have completed augmenting control objects.

Functional Example

Here is an example showcasing how to utilize the Places Library API:

var appMaps = angular.module('appMaps', ['uiGmapgoogle-maps']);
appMaps.config(function(uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
        libraries: 'places'
    });
})
appMaps.controller('mapController', function($scope,uiGmapIsReady) {
    
    $scope.map = { 
           center: { latitude: 40.1451, longitude: -99.6680 }, 
           zoom: 4, 
           bounds : {northeast : { latitude : 79.08815460000005, longitude : 79.08815460000005},
                   southwest : { latitude : 79.08815460000005, longitude : 79.08815460000005}},
           control: {},
           events: {
              click: function(map, eventName, originalEventArgs){
                  var e = originalEventArgs[0];
                  $scope.geocodePosition(e.latLng);                 
              }
           }                 
    };
    
    $scope.markers = [];
     
    
    $scope.geocodePosition = function(pos) {
       var map = $scope.map.control.getGMap();
       var service = new google.maps.places.PlacesService(map);  
       var request = {
          location: pos,
          radius: '500',
          //types: ['store']   
       };
       service.nearbySearch(request, function(results, status) {
           if (status == google.maps.places.PlacesServiceStatus.OK) {
              var place = results[0];
              alert(place.name);
           }
       });
    };
    
   
    
     uiGmapIsReady.promise().then(function(maps) {
        //...
     });
});
.angular-google-map-container {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
}
<script src="https://code.angularjs.org/1.3.14/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script src="http://rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
<div ng-app="appMaps" ng-controller="mapController">
    <ui-gmap-google-map center='map.center' zoom='map.zoom' control='map.control' id="map-canvas" events="map.events">
        <ui-gmap-markers models="markers" idkey="markers.id" coords="'coords'" events="markerEvents" >
        </ui-gmap-markers>
    </ui-gmap-google-map>
</div>

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

How can filters be effectively utilized alongside transclusion within directives?

Seeking advice on applying a filter to the transcluded text within my directive. Struggling to determine the best approach, I currently have a working version that utilizes the compile function to access the transcluded text. Take a look at this JSFiddle ...

Incorporating jQuery Masonry for seamless overlapping effect while implementing infinite scroll

I've developed a script that enables infinite scrolling on my website: $(document).ready(function() { function getLastId() { var lastID = $(".element:last").attr("id"); $.post("2HB.php?action=get&id=" + lastID, ...

Is it possible to achieve dynamic updating in Angular without utilizing ng-repeat? (with the use of Firebase)

Is there a way to dynamically update the DOM without utilizing ng-repeat in your template? It appears that when using ng-repeat to load a list of objects, any additions or deletions from the database automatically reflect in the DOM. However, if I simply u ...

Disabling a checkbox within an onClick event handler

I'm facing an issue where I have a checkbox with the type "checkbox" and I'm using JAWS to read it. The problem is that in IE11, JAWS reads a disabled checked checkbox as unchecked, which I believe is a bug in IE. To work around this, I need to r ...

convert an array into a JSON object using JavaScript

Is there a way to convert the following array structure arr = [{ "a":1, "b":2, "c":c }] into a JSON object format? arr = { "a":1, "b":2, "c":c } ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

Is it possible to simultaneously send a JSON object and render a template using NodeJS and AngularJS?

I'm currently facing issues with my API setup using NodeJS, ExpressJS Routing, and AngularJS. My goal is to render a template (ejs) while also sending a JSON object simultaneously. In the index.js file within my routes folder, I have the following s ...

Avoid opening the page when attempting to log in with jquery, ajax, and php

I am facing an issue with my code. I have a file named "index.html" which contains a login form. Another file called "dash.js" retrieves the username and password from the login form and redirects to "connectdb.php" to check the login credentials with the ...

Is there a way to determine the actual time or percentage completion of a file upload using Telerik RadUpload?

Utilizing the Telerik upload file control with manager is a key component of my project: <telerik:RadUpload ID="RadUpload" Runat="server" MaxFileInputsCount="5" /> <telerik:RadProgressManager ID="RadProgressManager" Runat="server" /> For clie ...

Is it possible to continuously refresh a DIV element?

After spending the past 4 or 5 hours scouring Stack and various other resources, I am still unable to find a solution to my problem. The issue at hand involves an Iframe within a page that displays 5 lines of information fetched from a database. This info ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

Retrieving specific value from a Parent Controller in AngularJS using UI Router

I have a request to display the value stored in $scope.resAVal on my index.html page. This value is accessible within the RootCtrl. index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <!-- any required JavaScript librarie ...

Is there a way to retrieve the value of elements that are deeply nested within multiple objects and arrays?

When making an API call to retrieve data from the Google Distance Matrix API, I store that information in my Redux store within a React application. The returned data object is structured as follows: Object { "destination_addresses": Array [ "21 Fo ...

Get the docx file as a blob

When sending a docx file from the backend using Express, the code looks like this: module.exports = (req, res) => { res.status(200).sendFile(__dirname+"/output.docx") } To download and save the file as a blob in Angular, the following code snippet i ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Retrieving JSON data from a URL with PHP

Attempting to retrieve JSON data from the following URL: $search_data&format=json&nojsoncallback=1 The information I am aiming to obtain based on the above link is as follows: { "places": { "place": [ { ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

Sending data from MongoDB API to HTML in Electron using parameters

I am currently developing an Electron application for my personal use and utilizing MongoDB Atlas as the backend for my Node application. As I am relatively new to Electron, I am still experimenting with different approaches, so there might be some minor m ...

What is the best way to access the primitive value of an attribute directive in

I'm having trouble retrieving the actual value of a directive attribute. Instead of getting the raw value, I keep getting the literal attribute name. --HTML <input my-directive="5==5" /> <div my-directive="isFoodReady()"> <!--some c ...

instructions for selecting div id within the same "table td" element using jQuery

Here is the code snippet that I am working with: <td> <div id="div<%# Eval("Id") %>" class="Display"><%# Eval("Display") %></div> <div class="Actions"> </div> <div class="Comment"> <span>Comm ...