Map Infobox appearing on page load

I am working on a Google map project where markers and info boxes dynamically populate when the user clicks on the map. However, I now need the info box to be loaded initially when the map loads, without requiring a click event. I have tried writing some code for this purpose but it is not functioning as expected. Any help would be greatly appreciated.

$scope.map = {
            center: {
                latitude: 0,
                longitude: 0
            },
            zoom: 1,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            control: {}
        };

        // place a marker
        $scope.markers = [];

        function setMarker(lat, long, title, content) {
            var marker = {
                id: $scope.markers.length+1,
                coords: {
                    latitude: lat,
                    longitude: long
                },
                options: {
                    title: title,
                    icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png'
                },
                events: {
                    click: function(marker, eventName, args) {
                        // close window if not undefined
                        var infoWindow;
                        if (infoWindow !== void 0) {
                            infoWindow.close();
                        }
                        // create new window
                        var infoWindowOptions = {
                            content: content
                        };
                        infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                        infoWindow.open($scope.map, marker);
                    }
                }
            };
            $scope.markers.push(marker);
        };

Here is my updated code to load the info box when the map loads, replacing the initial click event method:

window.onload = function(e){ 

 var infoWindow;
if (infoWindow !== void 0) {
    infoWindow.close();
}
// create new window
var infoWindowOptions = {
    content: content
};
infoWindow = new google.maps.InfoWindow(infoWindowOptions);
infoWindow.open($scope.map, marker);

}

Answer №1

This sample code (adapted from the Google Maps Info Windows example) showcases how to display an info window once the map has finished loading

angular.module('mapApp', [])

    .controller('mapCtrl', ['$scope', function ($scope) {

        $scope.map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: -25.363, lng: 131.044 },
            zoom: 4
        });


        var contentString = '<div id="content">'+
            '<div id="siteNotice">'+
            '</div>'+
            '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
            '<div id="bodyContent">'+
            '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
            'sandstone rock formation in the southern part of the '+
            'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) '+
            'south west of the nearest large town, Alice Springs; 450&#160;km '+
            '(280&#160;mi) by road. Kata Tjuta and Uluru are the two major '+
            'features of the Uluru - Kata Tjuta National Park. Uluru is '+
            'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
            'Aboriginal people of the area. It has many springs, waterholes, '+
            'rock caves and ancient paintings. Uluru is listed as a World '+
            'Heritage Site.</p>'+
            '<p>Attribution: Uluru, <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
            'https://en.wikipedia.org/w/index.php?title=Uluru</a> '+
            '(last visited June 22, 2009).</p>'+
            '</div>'+
            '</div>';

        $scope.infoWindow = new google.maps.InfoWindow({
          content: contentString
        });
        
        $scope.marker = new google.maps.Marker({
          position: {lat: -25.363, lng: 131.044},
          map: $scope.map,
          title: 'Uluru (Ayers Rock)'
        });
        $scope.marker.addListener('click', function() {
          $scope.infoWindow.open($scope.map, $scope.marker);
        });
        $scope.infoWindow.open($scope.map,$scope.marker); 
        


    }]);
#map 
{
    height: 480px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<div ng-app="mapApp"  ng-controller="mapCtrl" >
  <div id="map"></div>
</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

Clicking on the (x) button element will eliminate the DOM node from a list

https://i.stack.imgur.com/GxVYF.png A value is being dynamically added to my page, and here is the code snippet: function favJobs(data){ number_of_jobs_applied = data.total_bookmarked; $('.bookmark-title').append(number_of_jobs_applied, " ...

Tips on how to collapse all elements whenever one is being opened in a FAQ card using ReactJS

Clicking on a question reveals its text, and clicking on another collapses the previous one. The issue arises when trying to close an open question by clicking on it again - it doesn't work as intended due to a potential error in the If statement [im ...

Angularjs is struggling to connect data to the user interface

It seems that the array is not binding properly in the UI. In the HTML code, I am using dataTables. The variable $scope.successMessage is also not binding to the UI. I have tried multiple approaches but none seem to be working. Here is a snippet of th ...

Using an expression from the parent controller to disable an item in an AngularJS directive

I created a list of custom directive items, each with a remove button. The issue I'm facing is that I want to disable the remove button when there's only one item left in the list, but it's not working as expected. To see this problem in ac ...

What is the best way to properly format letters with accents (such as French letters)?

I have encountered a challenge where I created a PHP file to display French text and then utilized this text in an AJAX file (specifically the responseText). The issue arises when trying to show the French responseText in an alert using JavaScript, as ac ...

Rotate the image as you swipe left or right with Angular's ng-swipe-left and ng-swipe-right features

I am currently utilizing angular's ng-swipe-left and ng-swipe-right to detect swipe events on touch devices. My goal is to rotate an image based on the speed and direction of the swipe while it is still in progress. However, I am facing a challenge as ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

Utilizing PHP and jQuery to dynamically populate Google Maps with multiple markers

I am currently working on integrating a Google map with a database to dynamically display multiple markers using PHP and MySQL. Below is the code I have been using: <?php //This section retrieves data from the database for later use in jQuery //CREATE ...

Selenium on Sauce Labs does not successfully load the page in Firefox after clicking

An issue has arisen where a test that functions properly with selenium webdriver locally is timing out when executed remotely on saucelabs.com. Notably, the test runs smoothly for Chrome in both local and remote scenarios. The problem seems to lie in the ...

Unable to access child props in parent event handler in React

Currently utilizing React for building a UI, the structure involves a parent component and a child component as shown below: // Child Component var ListItem = React.createClass({ render: function() { var link_details = ( <div> ...

Extracting the value from a Text Editor in React Js: [Code snippet provided]

Currently, I am in the process of developing a basic app that generates a JSON form. So far, I have successfully incorporated sections for basic details and employment information. The basic details section consists of two input fields: First Name and Las ...

Click on a designated button to choose a specific file on an HTML page

I need to be able to select a specific file by clicking on another button. A helpful solution that utilizes JavaScript to trigger the selection of a hidden file can be found in this answer. You can view the implementation here. In my scenario, I alre ...

How can I implement two dropdowns in jquery?

One of my dropdown menus is currently utilizing this code to fetch the selected value: $(document).on('change','#DropDown1',function() { var value1 = $(this).children("option:selected").val(); var data = {"key": value1}; ...

The nearby diversion inexplicably triggers a phantom GET request

My goal is to build a website with specific functionality: If a user tries to access the /home page without authentication, they should be redirected to the /login page. After successfully logging in on the /login page, the user should receive a session c ...

Can someone guide me on how to retrieve data from a MUI table within a React project

Currently, I am retrieving data from a server in JSON format and looping through this data to display specific information. Everything is functioning as expected, but I'm encountering an issue with a Popover element that contains items with onclick ev ...

Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component ...

Layout display issue post redirection in React

I am facing an issue with my app that utilizes styled-components and material-ui. I have set up private routes based on user roles, and when a non-authenticated user is redirected to the login page, the layout fails to load properly. App.tsx import React ...

I'm all set to launch my express js application! What are the major security concerns that I need to keep in

As a beginner in deploying express applications, I find myself lacking in knowledge about the essential security measures that need to be taken before launching a web application. Here are some key points regarding my website: 1) It is a simple website ...

I specialize in optimizing blog content by omitting the final line within a React framework

https://i.stack.imgur.com/WKOXT.png Currently, I have 4 lines and the 5th line in the current input field. This is my React code snippet: import { FC, useEffect, useState } from "react"; interface BlogWitterProps {} const BlogWitter: FC<B ...