How to show infoWindows in GoogleMaps using AngularJS

Could you lend a hand with my query? In my web page, thanks to angular js v1, there's an embedded map that:

  • Enables users to input an origin and destination.
  • Plots markers and showcases the route from the origin to the destination.
  • Shows restaurants (as markers) for waypoints at the origin, destination, and a midpoint. This reduces overuse of Google API requests.

The Issue: The InfoWindow doesn't show up when I click on my markers. While it appears by default for the origin and destination points, I'm struggling to make it appear for all the restaurant markers. I used PlaceSearch for this purpose.

I've done extensive research online, but being new to JS/Angular, I can't find the best solution.

Below is my directive code, along with some InfoWindow snippets, but I'm stuck. I'm not sure if a click handler is necessary?

    googleMap.$inject = [];
     function googleMap() {

    return {
     restrict: 'E',
     template: '<div class="google-map"></div>',
     replace: true,
     scope: {
       center: '=',
       zoom: '=',
       origin: '=',
       destination: '=',
       travelMode: '='
    },

    link($scope, $element) {
      const map = new google.maps.Map($element[0], {
        zoom: $scope.zoom,
        center: $scope.center
      });

      const directionsService = new google.maps.DirectionsService();
      const directionsDisplay = new google.maps.DirectionsRenderer();
      const placesService = new google.maps.places.PlacesService(map);
      // const infoWindows = [];
      // const infowindow = new google.maps.InfoWindow();
      // let marker = new google.maps.Marker;

      directionsDisplay.setMap(map);

      $scope.$watch('center', () => map.setCenter($scope.center), true);

      $scope.$watchGroup(['origin', 'destination', 'travelMode'], 
    displayRoute);

      // DISPLAY ROUTE
      function displayRoute() {
        if(!$scope.origin || !$scope.destination || !$scope.travelMode) 
    return false;

        directionsService.route({
          origin: $scope.origin,
          destination: $scope.destination,
          travelMode: $scope.travelMode
        }, (response) => {

          directionsDisplay.setDirections(response);

          // beginning of this form
          // response.routes[0].legs[0].steps.map(step => {
          const steps = response.routes[0].legs[0].steps
          const lookup = [steps[0], steps[Math.round(steps.length / 2)], 
          steps[steps.length - 1]]
          lookup.map(step => {


            placesService.nearbySearch({
              location: step.start_point,
              radius: 50,
              type: ['restaurant'],
              openNow: true
            }, (results) => {
              results.map(place => {
                console.log(place.name);
                return new google.maps.Marker({
                  map: map,
                  position: place.geometry.location,
                  // label: '⭐️',
                  title: place.name
                });  //google maps marker
              });

              results.map(place => {
                console.log(place.vicinity);
                const contentString = place.name;
                return new google.maps.InfoWindow({
                  title: place.name,
                  content: contentString
                });  //google maps marker
                // infoWindows.push(infowindow);
              });


            });
          }); //end of this function

        });  //end return directionsdisplay
      }  //display route ends


    } //link scope ends
  };
}

export default googleMap;

Appreciate your help!

Answer №1

One way to accomplish this task is by first creating the infowindow and marker, then binding a click event to toggle the infowindow's visibility.

    var marker = new google.maps.Marker({
        position: latlng,
        map: mapObject,
        title: "MARKER"
    });

    var infoWindow = new google.maps.InfoWindow({
        content: "<h1>Hello World</h1>"
    });

    google.maps.event.addListener(marker, "click", function () {

         infoWindow.open(mapObject, marker);

    });

UPDATE - If you are dealing with an array or list of markers where each has its own info window, you can modify the code for plotting markers(results) like so:

Note: No compiler used, potential syntax errors may exist

// keep track of plotted markers to clear if needed
var markers = [];

for (var i = 0; i < results.length; i++) {

    var place = results[i];

    // create marker    
    var marker = new google.maps.Marker({
      map: mapObject,
      position: place.geometry.location,
      title: place.name
    });

    // create info window
    var infoWindow = new google.maps.InfoWindow({
      content: ''
    });

    //add extra property to marker(infoWindow) for access in click event handler
    marker.infoWindow = infoWindow;

    // click event listener
    google.maps.event.addListener(marker, "click", function() {

        // 'this' refers to marker 
        var map = this.infoWindow.getMap();

        if (map !== null && typeof map !== "undefined")
            this.infoWindow.close();
        else {
            // open info window at marker position
            this.infoWindow.open(mapObject, this);
        }
    });
    markers.push(marker);
}

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

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Using breeze.EntityQuery.from('Agencies') will give you the final entity that was returned in the overall results

Greetings, I am new to breeze and apologize in advance if my issue turns out to be a rookie mistake on my part. I am currently working with Angular, specifically John Papa's hot towel base. I have created a repository that retrieves a list of agencie ...

Using jQuery to iterate through JSON data obtained from a web service

In this code snippet, I am attempting to retrieve a JSON response from a PHP page and then iterate through it to display the name field of each JSON object. However, for some reason, nothing is being alerted out. <html> <head> <title>A ...

What is the best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...

Switching between multiple views to a single view using Angular UI-router

I am working on an application that consists of three views (ui-view using Angular ui-router): header, sidebar, and content. Here is a simplified version of my index.html: <body> <div ui-view="header" class="..."></div> <div ...

How can I display an array with keys from php in AngularJS using ng-repeat?

I have a rootScope variable that will store product categories, each category may or may not have child categories. Here is how I assign the rootScope: $rootScope.categoryList = $http.get('category').then((result) -> result.data) This code s ...

What is the best way to use AJAX to navigate to a different webpage while sending data along with

After successfully saving a form and receiving a success message, I am able to redirect to another page using window.location.href = '/home'; with no issues. However, I would like to pass the success message to the home page after the redirect. W ...

Utilizing Ajax for Multiplication

Is there a way to dynamically calculate and display the total amount by multiplying the unit price with the quantity entered in the text box as it changes? <div> <label id="" name="price" class="unitprice"><?php echo "Price: <label ...

Press Button to create cookie and store it in Drupal 7

I am currently working on my Drupal 7 local website, which features an article and a popup on the homepage leading to that article. Within the article, there is a button that I want to serve as a way for users to dismiss the initial popup permanently. My i ...

How can I randomly choose 5 TR items and show them to the user?

How can I randomly select and display 5 questions for the user? The rest of the questions should be hidden on the page and only 5 questions should be displayed. This is a sample code. I want the user to see 5 questions out of many questions when the page ...

Add a fresh text field with the click of a button and delete it with another button in Laravel 4

My form includes two fields: phone and email, as shown in the image below. By clicking on the plus button, I would like to add an additional text field to the form below the button. Similarly, by clicking on the minus button, I want to remove the text fie ...

How can the token be verified when authorizing Google OAuth 2.0 on the server side?

Unable to validate the user token ID on the server side despite following Google's guide at https://developers.google.com/identity/sign-in/web/backend-auth In JavaScript, I retrieve the id token and send it to the server: var googleUser = auth2.cur ...

Unable to view flash elements in HTML using Django framework

Apologies for any errors in my English, I will do my best to explain clearly. I am new to working with Django and I have a html page with flash content called map.html. I would like to include this page into another page called soporte.html (which extends ...

Retrieving input values with JQuery

HTML <td data-title="Quantity"> <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10"> <button class="btn-minus bg_tr d_block f_left" data-item-price="8000.0" data-direction= ...

AngularJS - Retaining the initial value without submitting

On the left side, I have a list of users with corresponding details displayed on the right. The form handles the details on the right using inputs with ng-model. Whenever I click on a user from the left section, the selected user changes and the model auto ...

Tips for displaying a pop-up child `tr` element when clicking on each `tr` element in Angular

I am working with a table that utilizes ng-repeat. <table> <thead> <tr> <th>Assets</th> <th>Location</th> ...

Dynamic text modification through background color adjustments with Javascript

I have created a JavaScript function that changes the background color of a website, but I am wondering if there is a way to also change the text in the body of the page when this color change occurs. function updateContent(element, curColorNumber){ ...

Tips for displaying "onclick" content beside dynamically generated content

I am working on a feature where a dynamically generated list has radio buttons displayed next to it. The goal is to show a dropdown list next to the specific radio button and list item that was changed. Essentially, if the radio button is set to "yes," I w ...

Can WebAssembly code be executed asynchronously?

I've created a C function that can be run from Angular/TypeScript/JavaScript using WebAssembly. testWebAssembly() { Module.ccall("aCFunction", null, [], []); // takes a few seconds to finish } This particular function involves complex mathematic ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...