After running the map.fitBounds function, you can retrieve the current boundary coordinates using map.getBounds() in

After calling fitBounds() to recenter and zoom the map to fit the bounds, I expected getBounds() to return a valid bound. However, it is returning nil.

Below is the code snippet that reproduces this issue:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

        <style>
            #map {
                width: 800px;
                height: 400px;
            }
        </style>

    </head>
    <body>
        <div id='map'></div>

        <script>
            var myLatlng1 = new google.maps.LatLng(-38.397, 150.644);
            var myLatlng2 = new google.maps.LatLng(-34.897, 150.844);
            var myLatLngBounds = new google.maps.LatLngBounds(myLatlng1, myLatlng2);

            var myOptions = {
                  mapTypeId: google.maps.MapTypeId.ROADMAP,
                  center: new google.maps.LatLng(0, 0),
                  zoom: 0
            }

            var map = new google.maps.Map(document.getElementById("map"), myOptions);

            map.fitBounds(myLatLngBounds);

            console.log(map.getMapTypeId());
            console.log(map.getZoom());
            console.log(map.getBounds());
        </script>
    </body>
</html>

Is there something I'm missing here? I couldn't find any relevant information in the documentation. The closest I found is a note on getBounds stating:

If the map is not yet initialized (i.e. the mapType is still null), or center and zoom have not been set then the result is null.

Additionally, getZoom also returns undefined. Does fitBounds() not set this value?

EDIT I have made updates to the code by adding a default zoom and center, following Marcelo's suggestions.

Answer №1

Following the advice of @CrazyEnigma, you can retrieve the bounds once the bounds_changed event occurs:

map.fitBounds(myLatLngBounds);

google.maps.event.addListener(map, 'bounds_changed', function() {
  console.log(map.getMapTypeId());
  console.log(map.getZoom());
  console.log(map.getBounds());
});

The above code will display the following information in your console:

roadmap
6
Object

Remember, if you only need to getBounds and perform an action once, you can use addListenerOnce instead of addListener (Thanks, @Tomas).

Answer №2

Ensure to retrieve the boundaries once the bounds_changed event has occurred.

Answer №3

Implement addListenerOnce for tilesloaded event

google.maps.event.addListenerOnce(map, 'tilesloaded', function(){ 
map.setCenter(myLatLngBounds)
});

Answer №4

Your unique solution lies within your own words. Remember to specify the center point and zoom level to properly initialize the map.

It's worth noting that according to the MapOptions object specification, the values for center and zoom are essential components:

http://example.com/maps/reference.html#MapOptions

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

Tips for waiting for an event from a specific element in Playwright

Is there a way to await an event on a specific element using Playwright? Similar to page.waitForEvent, but focusing only on a particular element rather than the entire page. More information can be found in the documentation. ...

grab the destination URL from the embedded frame

Thank you for your attention. I am working with three iframes spread across different HTML documents. Here is how they are organized: In the file iframemain.html, there is: <iframe src="iframeparent.html" width="100%" height="600"> </iframe> ...

Setting the default selected row to the first row in ag-Grid (Angular)

Is there a way to automatically select the first row in ag-grid when using it with Angular? If you're curious, here's some code that may help: https://stackblitz.com/edit/ag-grid-angular-hello-world-xabqct?file=src/app/app.component.ts I'm ...

Angular is encountering a situation where code is being executed before properly waiting for the response from an asynchronous

I am in need of a solution that will ensure my function waits for a response before proceeding. I want to prevent the response from being empty and ensure that my code waits for the completion of the asynchronous call. asyncReq(element: any) { this.confl ...

Issue with div element not stretching to 100% width

I am currently working on a fluid layout design where the template includes a header, menu, and body section. <div class="w100 h100"> <div id="headerBox" style="height: 10%;" class="w100"> <div style="width: 80%;" class="lfloat ...

Managing the transition of the object in question

I am in the process of designing a navigation bar. I have created an array to store the information of the tabs present in the nav bar. tabs: [ { name: 'All',id: "dash.courses.all", to: 'all', curre ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

The JavaScript array slideshow is experiencing some glitches in its transition

After diving into JavaScript recently, I managed to center a div and make it fullscreen as the window resizes. However, things got tricky when I added a script I found online to create an image transition using an array. Unfortunately, these scripts are co ...

Executing JavaScript code within ASP.NET Visual Basic

My current web application uses jQuery and JavaScript, but I want to add more features that are supported in ASP.net VB. However, I am unsure if the JavaScript can run after the VB code. Essentially, I would like the web app to follow this sequence: ...

When you reach a scrolling distance of over 300 vertical heights,

Is it possible to show and hide a class based on viewport height? I am familiar with displaying and hiding a class after a specified pixel height, but I'm wondering if it's achievable using viewport height instead? Specifically 3 times the viewp ...

Trouble confirming the password field with regular expressions in angular.js

I'm trying to validate my password field with specific special characters requirements. The field must contain at least one number, upper case letter, lower case letter, and an underscore, all of which are mandatory. I have attempted to achieve this u ...

Conceal the slider thumb within the material-ui framework

I've been attempting to conceal the slide thumb, initially without using a library. However, I started considering utilizing material-ui as it might make the process easier. Hence, I'm seeking assistance here. Below is my code snippet: import * ...

Struggling to make the controller karma test pass

I am currently working on developing a "To Do list" using angular js. My goal is to allow users to click on a checkbox to mark tasks as completed after they have been finished. While the functionality works fine in the index.html file, I am struggling to p ...

The Loading Screen Is Lagging

I hope I'm not overwhelming you with too much (or too little!) information. It's a bit tricky for me to share code when it spans multiple files like this. So, in my small project, I have my app.js server using express and ejs. There's a &qu ...

The Chrome file storage system saves information in files

My challenge is to save data obtained from the Chrome geolocation API into a text file using the Chrome fileSystem API. However, despite successfully creating a file, it remains empty after the process. To simplify, I attempted to add the string '1234 ...

modifying button depending on the state of bootstrap collapse

I'm currently utilizing Bootstrap in my project. Here is the snippet of HTML code I have: <div class="row"> <button id="dog-btn" data-toggle="collapse" data-target="#dog-section" onclick=" ...

Tips for utilizing JavaScript to engage with a Cisco call manager

Our team is currently working on an IVR web application built with node js. I am wondering if it is feasible to integrate with the cisco unified call manager directly through node js in our web application? ...

Incorporate the value of a JQuery variable within an HTML form

When the Submit button is clicked, I am attempting to pass the value of currentDate to a REST GET service. However, there are two things that I don't understand. Is it possible to include the URL of the REST service in the action attribute of the fo ...

Adjust the node_modules path tailored to your project

My current project structure looks like this: |-app |-... |-libs |- package.json |- index.html I am interested in organizing my project such that the 'node_modules' folder is inside the 'libs' folder. The desired structure is as fo ...

Flask app facing compatibility issues with jQuery .getJSON

I am encountering an issue with my flask application where I am attempting to send JSON data to the browser and render it. However, the line containing $.getJSON() is not executing as expected. Here is a breakdown of the relevant code: app.py from flask ...