Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup:

 <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'"  events="mapResult.events"  >

                                    <ui-gmap-windows show="show" closeClick="closeClick()">
                                         <div ng-controller="MapsDemoCtrl" ng-non-bindable>

                                                <span style="color:#000;font-weight:bold;">
                                                     Formname :  <a href='#/formspostview/{{id}}' style="color:#000;">
                                                                    {{form_name}}
                                                                 </a><br>
                                                     Username :   {{user_name}}<br>

                                                     Date     :   {{createdAt | date: "MM/dd/yyyy H:mm"}}<br>      
                                                </span>   

                                      </div>
                                    </ui-gmap-windows>
                                </ui-gmap-markers>

This is how I've set it up on the controller side:

$scope.onclick = function () {
    // check if there is query in url
    // and fire search in case its value is not empty
    console.log("hai");
};

I'm struggling to get the marker event to work. Can anyone provide guidance on how to properly use the marker event?

Answer №1

Here is an illustration on how to link the click event handler to a marker using the ui-gmap-markers directive:

$scope.map.markersEvents = {
      click: function (marker, eventName, model, args) {
          //...
      }
};

Consider the following:

<ui-gmap-markers models="map.markers" coords="'coords'" icon="'icon'" options="'options'" events="map.markersEvents">          
</ui-gmap-markers>

Example in action

angular.module('appMaps', ['uiGmapgoogle-maps'])
  .controller('mainCtrl', function ($scope, $log) {
      $scope.map = {
          center: { latitude: 40.1451, longitude: -99.6680 },
          zoom: 4,
          markers: [
          {
              id: 0,
              showWindow: false,
              city: 'New York',
              coords: {
                  latitude: 40.710355,
                  longitude: -74.001839
              }
          },
          {
              id: 1,
              showWindow: false,
              city: 'San Francisco',
              coords: {
                  latitude: 37.775404,
                  longitude: -122.437600
              }
          }]
      };
      $scope.options = { };

      $scope.map.markersEvents = {
          click: function (marker, eventName, model, args) {
              logMarkerInfo(marker);
          }
      };


      var logMarkerInfo = function(marker){
         var pos = marker.getPosition();
         document.getElementById('output').innerHTML += "Marker (" + pos.lat() + "," + pos.lng() + ")";
      };  

  });
html, body, #map_canvas {
            height: 100%;
            width: 100%;
            margin: 0px;
}

#map_canvas {
            position: relative;
}

.angular-google-map-container {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
}
<html xmlns:ng="http://angularjs.org/" ng-app="appMaps">
<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 id="map_canvas" ng-controller="mainCtrl">
        <ui-gmap-google-map center="map.center" zoom="map.zoom" options="options">
            <ui-gmap-markers models="map.markers" coords="'coords'" icon="'icon'" options="'options'" events="map.markersEvents">
                <ui-gmap-windows show="map.showWindow" closeclick="'closeClick'" >
                    <div ng-non-bindable>{{ city }}</div>
                </ui-gmap-windows>
            </ui-gmap-markers>

        </ui-gmap-google-map>
</div>
<div id="output"/>

Answer №2

Here is another way to achieve the same result: (Ensure $interval is injected into your controller)

var ctrl = this;

var count = 1;

var clock;

ctrl.map;

var lat = -23.56;

var long = -46.65;

// Start Hold To Mark Controller
var startCount = function(event){
  count = 1;
  if ( angular.isDefined(clock) ) return;
  clock = $interval(function() {
    if(count > 0){
      count = count - 1;
    } else{
      addMarker(event.latLng);
      stopCount();
    }
  }, 500);
};

var stopCount = function(){
  if (angular.isDefined(clock)) {
    $interval.cancel(clock);
    clock = undefined;
  }
};

$scope.$on('$destroy', function() {
  stopCount();
});
// End Hold To Mark Controller

// Start GoogleMaps Map Controller
function initMap() {
  if(lat == null || long == null){
    var center = { lat: -23.56, lng: -46.65 };
  } else{
    var center = { lat: lat, lng: long };
  }

  ctrl.map = new google.maps.Map(document.getElementById('map'), {
    disableDefaultUI: true,
    zoom: 12,
    center: center
  });

  google.maps.event.addListener(ctrl.map, 'mousedown', function(event) {
    startCount(event);
  });

  google.maps.event.addListener(ctrl.map, 'mouseup', function(event) {
    stopCount();
  });

  google.maps.event.addListener(ctrl.map, 'dragstart', function(event) {
    stopCount();
  });
};

function addMarker(location) {
  var marker = new google.maps.Marker({
    animation: google.maps.Animation.DROP,
    draggable: true,
    position: location,
    map: ctrl.map
  });
  markers.push(marker);
};

initMap();
// End GoogleMaps Map Controller

This method will place a marker after a one-second hold, but if you release your finger or move it before that time elapses, the marker won't be created.

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

Why is the Twitch api map function returning nothing, while the console log is showing output?

Presently, my Nextjs page is making multiple Twitch API calls successfully and displaying the correct data. However, one of the mapping functions is failing to render anything on the page, even though the console log shows the data. Although I am relativel ...

The touchstart event handler triggers but the event returns as undefined

@ontouchdown="handleTouch(event)" handleTouch(event) { console.log(event); console.log("touch event"); } Why is the event not being passed properly? ...

Unusual CSS hierarchy observed post AJAX content load

Currently, I am facing a puzzling issue where my CSS rules seem to be losing precedence on a page loaded via AJAX. Despite placing my custom CSS file last in the main page, allowing it to take precedence over any bootstrap styles, after loading new content ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

Unable to grab hold of specific child element within parent DOM element

Important Note: Due to the complexity of the issue, the code has been abstracted for better readability Consider a parent component structure like this: <child-component></child-component> <button (click)="doSomeClick()"> Do Some Click ...

Developing dynamic HTML content using Android and JavaScript to insert JavaScript code into the head tag dynamically

I need to incorporate a banner into my Android application in a specific way. Upon receiving the following Javascript code from the server: <script type="text/javascript" src="http://rm.face.ua/adriver.core.2.js"></script> <div id="adri ...

interrupt the node script using async behavior

I encountered an issue while running the npm install command to install a list of modules on Node, specifically related to async. TypeError: undefined is not a function What could be causing this problem? var fs = require( "fs" ), path = require( ...

Determining If Props Have Been Undefined In React

Greetings and thank you for taking the time to read this: I am currently working through a tutorial that can be found here: My issue lies in the creation of an author, where the application is trying to load the URL of the current author's ID, which ...

What sets apart the $ and $() functions in jQuery?

After reviewing the jQuery API, I noticed that $() represents a collection of matched elements. However, I am curious about the significance of $. An example from the imagesLoaded library is provided below. if ( $ ) { $.fn.imagesLoaded = function( opt ...

AngularJS navigates to specific URL paths instead of only displaying the corresponding HTML pages

Building a simple AngularJS application using the angular-seed starter template consists of: index.html app.js home/home.html home/home.js My objective is to navigate to home.html when clicking on the Home li item with the href="/home". However, the cur ...

Is it possible to pass a JavaScript array to a local variable by reference?

Within my namespace, I have an array defined in JavaScript like this: app.collection.box = []; Additionally, there is a function within the same namespace structured as follows: app.init = function () { var box = this.collection.box; // ... code ...

How can I adjust the transparency in a JavaScript popup modal window for an ASP.Net GridView?

Recently, I added an 'onclick' event to every row of an asp gridview and the popup window that appears is functioning perfectly. Now, I'm interested in adding a transparency level to the body of the popup window for a translucent effect. Can ...

When attempting to set a dynamic src tag for embedding a Google Map in a React application, an X-Frame-Options

I'm attempting to display a specific location using an iframe embed from Google Maps (shown below): <iframe width="100%" height="200" frameBorder="0" scrolling="no" marginHeight={0} marginWidth={0} id="g ...

Guide on using POST method in jQuery version 1.11.4 for tab functionality

I'm currently in the process of upgrading from jquery ui version 1.9.2 to jquery ui version 1.11.4 and I've encountered a situation where ajaxOptions has been removed from the tabs control. Originally, I was using the following code: $("#tabs"). ...

Update object properties in Angular controller dynamically

Take a look at my simple plunker Within the code, I am attempting to link a scope variable to an object property. $scope.name = 'World'; var obj = { "name":$scope.name } $scope.$watch('name', function(){ console.log(obj["name"]); ...

What is the best way to implement a nested lookup in MongoDB within a field?

Within my database, I have a collection named Randomhospital. Inside this collection, there is a field named hospital structured as follows: { "id": "GuDMUPb9gq", "Hospital Name": "UPHI", "Hospital City&qu ...

Angular 2 is not recognizing the element 'router-outlet'

I am currently utilizing universal-cli... This is how my app.node.module.ts appears: /** * This file and `main.browser.ts` are quite similar, for now! * By separating these, you can create logic, imports, etc that are "Platform" specific. * If you wis ...

Learn how to fetch user-selected options in Node.js and display the corresponding file contents in a textarea after submission

Hello, I am new to Node.js so please be patient with me. I am struggling to figure out how to retrieve the selected option from a drop-down list after a user submits it and then perform an action based on that choice. Here is an example of what I have in m ...

Strategies for Effectively Managing Null Checks in Your JavaScript Project

When retrieving data from the BE API, it is in the format: { "details": { "address": { "street": "123/4", "city": "Banglore" } } } In our React project, we access this dat ...