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

Is there a way to showcase individual components on a single surface one at a time?

Let me try to explain my issue as clearly as possible! I am currently working on a website using React and Material-UI. On one of my pages, I have a Paper component where I want to display different components that I have created, but only one at a time. ...

What is the best way to retrieve the value of a boolean property from a JSON object produced by Rails within an AngularJS expression?

Here's the story: So, I had this element with an ng-repeat directive and decided to use the ng-class directive on it. The purpose of adding the ng-class was to apply a specific class to the element based on certain conditions. But here's where t ...

Bizarre error when injecting Factory into Controller in AngularJS

After scouring through countless posts on various forums, I have yet to find a solution to my unique problem. I find myself in a peculiar situation where I am trying to inject a Factory into a Controller, and despite everything appearing to be in order, i ...

Using a toolbar to insert a hyperlink for hypertext communication

My journey with Javascript and React began this week, so I'm still getting the hang of things, especially in the front end domain. In my project, there's a link button within a toolbar. The idea is to click on it, have a text box pop up where yo ...

Arranging a dropdown list of options in alphabetical order using Javascript

Could you assist me in sorting my select list alphabetically? Below is the code I currently have:- $.getJSON("php/countryBorders.geo.json", (data) => { $select.html(""); for (let i = 0; i < data["features"].leng ...

Ways to adjust the text size in jqGrid?

The current theme is ui-lightness. How can I adjust the font size within the grid? Your suggestions are appreciated. Many thanks. ...

Alter appearance of images depending on browser window size

I am working on an angular JavaScript code snippet that uses the ng-repeat command to display a row of small images. I want to ensure that these images do not spill over into a second line when the browser window is resized. Instead, I prefer them to eith ...

Retrieve the CSS class definition using the console in the Chrome Developer Tools

Is there a way to automatedly extract CSS class definitions from Chrome Developer Tools? I want to retrieve the styles defined in a specific class name, similar to how it is displayed in the Styles tab on the right-hand side. I know about the getComputedS ...

Can you please provide the syntax used for implementing an orderBy in an ng-repeat directive in AngularJs?

After reviewing the documentation at http://docs.angularjs.org/api/ng.filter:orderBy, I'm still a bit confused. It would be helpful to have a simple example along with a more detailed one in the documentation. Here is what I currently have: <tr d ...

playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects. After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly. My query pertai ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Tips for adding borders to specific rows and columns using ALASQL in Excel and AngularJS

Is it possible to add borders to specific columns and rows in my code? I've been trying but haven't found an option for it yet. columns: [ {columnid:'email'}, {columnid:'dob', title: &a ...

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

The appearance of all input forms in MaterializeCSS when used in an electron environment appears to

After following the instructions here on how to get started with Materialize CSS, I am having issues with my input form appearing strange: https://i.sstatic.net/lveS2.png The contents of my current index.html file are as follows: <!DOCTYPE html> &l ...

Updating the value property of an object within a loop dynamically in React

At the moment, I am utilizing an array of objects called "mainArr" as shown below, I have implemented a loop inside a function to filter object properties, but I want to dynamically replace obj.name with obj."param" based on the parameter passed. Both nam ...

Verify MVC Controller Authorization and respond with 401 Unauthorized to the AngularJS application

Currently, I have an AngularJS application that interacts with an MVC Controller to retrieve specific data. To ensure that users have the necessary permissions to execute certain actions on the controller, I've created a custom class called RBACAutho ...

What is the procedure for extracting data from a JSON file within an HTML document?

Hey there, I am currently working on reading data from a json file using ajax. I have created a Video object that consists of Courses objects with titles and URLs. However, when attempting to read the title and URL of HTML as an example, I am not seeing a ...