The initial zoom level on Google Maps does not adjust when using the fitBounds method for polyline

I am currently utilizing the fitbound function to automatically zoom in on a polyline displayed on a map. However, I have noticed that on the initial attempt, it does not work as expected. But if I make changes to the chartData and then call the same function again, it works perfectly fine. Here is the code snippet for the function:

var mapOptions = {
                    zoom: 1,
                    center: { lat: 0, lng: 0 },
                    zoomControl: true,
                    zoomControlOptions: {
                        style: google.maps.ZoomControlStyle.SMALL
                    },
                    mapTypeId: 'satellite'
                };
                this.chart = new google.maps.Map(document.getElementById(chart_element.id), mapOptions);
                let polylinePath = new google.maps.Polyline({
                    path: chart_data,
                    geodesic: true,
                    strokeColor: '#FF0000',
                    strokeOpacity: 1.0,
                    strokeWeight: 2
                });

                /* set auto zoom level to polyline */

                var latlngbounds = new google.maps.LatLngBounds();
                for (var i = 0; i < this.chartData.length; i++) {
                    latlngbounds.extend(this.chartData[i]);
                }

                this.chart.fitBounds(latlngbounds);

                /* Set polyline chart to map */
                polylinePath.setMap(this.chart);

https://i.sstatic.net/0dITS.png

Answer №1

// Adjust the zoom level
var zoomListener = google.maps.event.addListener((map), 'zoom_changed', function(event) {
    this.setZoom(11);
    google.maps.event.removeListener(zoomListener);
});

Answer №2

To enhance the functionality of google.maps.Polyline, consider adding a new prototype method called getBounds(). This method will allow you to scale the Map based on the boundaries of the Polyline's LatLngBounds. Simply set the map and then fit it to the bounds using the following code:

polyline.setMap(map);
map.fitBounds(polyline.getBounds());

Furthermore, there seems to be inconsistency in the naming convention within your code. The variable for the path is referred to as both chart_data and this.chartData.

var map;
var timeout;
var coordinates = [
  {lat: 37.772, lng: -122.214},
  {lat: 21.291, lng: -157.821},
  {lat: -18.142, lng: 178.431},
  {lat: -27.467, lng: 153.027}
];

var polyline = new google.maps.Polyline({
  path: coordinates,
  geodesic: true,
  strokeColor: '#FFD034',
  strokeOpacity: 1.0,
  strokeWeight: 2
});

var mapOptions = {
  mapTypeId: 'satellite',
  zoom: 20,
  zoomControl: true,
  zoomControlOptions: {
    style: google.maps.ZoomControlStyle.SMALL
  }
};

google.maps.Polyline.prototype.getBounds = function() {
  var bounds = new google.maps.LatLngBounds();
  this.getPath().forEach(function(e) {bounds.extend(e);});
  return bounds;
};

function onLoad() {

  /* creating the map and plotting the polyline */
  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);  
  polyline.setMap(map);
  
  /* initially fitting the map to bounds */
  map.fitBounds(polyline.getBounds());
  
  /* subsequent events, which fit the map to bounds (may prevent manual zoom). */
  google.maps.event.addListener(map, 'bounds_changed',
    function() {
      window.clearTimeout(timeout);
      timeout = window.setTimeout(function () {
        map.fitBounds(polyline.getBounds());
      }, 500);
    }
  );
}
google.maps.event.addDomListener(window, "load", onLoad);
html, body, #map_canvas {height: 100%; width: 100%; margin: 0px; padding: 0px;}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></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

Generate a series of inquiries from an API response and display them dynamically, complete with a text field and radio button for each question

Currently, I am in the process of developing a Question/Answer page using ReactJS. The questions are retrieved through an API call. I aim to present a series of radio buttons and text fields for users to respond to these questions. A "Panel" that resemble ...

What is the method to determine the size of a numbered list?

Currently transitioning from jQuery to plain JavaScript. Previously used this in jQuery: var list = $('.list li'), listLength = list.length; Now attempting to achieve the same with JavaScript, but encountering issues: var list = documen ...

What is the process for integrating a JOI validator with a Firebase function?

Is there a way to incorporate JOI validator into Firebase functions as middleware? When calling a Firebase function, it looks something like this: exports.createUserAccount = region("europe-east1").https.onCall(createAccount); // createAccount is ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

Tips for saving checkbox values in an array in the sequence they are selected

I need users to select items based on priorities, with a total of four items available. <input type="checkbox" value="1">Carrot <input type="checkbox" value="2">Apple <input type="checkbox" value="3">Banana <input ...

Tips for fixing a shader issue with a custom hover state shader on an image component in a React project utilizing react-three-fiber

I am currently working on implementing an image component with a hover effect using shaders in react-three-fiber. The shader I'm using was originally created by TheFrost and it can be found at https://codepen.io/frost084/full/OKZNRm. However, I am e ...

Firebase Cloud Function variables causing 'unidentified' output

While experimenting with firebase cloud functions, I'm encountering an issue with a constant error message stating that userID is undefined. It's preventing the function from running smoothly. https://i.sstatic.net/MsnsV.png Below is the databa ...

Troubles with AJAX and jQuery

<html> <head> <title>Ajax Example</title> <script type="text/JavaScript" src="jquery-1.5.1.min.js"></script> <script type="text/JavaScript"> function fetchData() { $.ajax({ type: "GET", url: "htt ...

Express.js Router Middleware: Body Parsing with Hyphens in req.body

I have set up a URL endpoint to receive parsed emails from Mailgun through their API. The URL is an Expressjs Route to MongoDB using body parser middleware. While the HTTP post to MongoDB works fine for simple text keys like 'sender', I encounter ...

Error in Javascript: Required variable missing for Sendgrid operation

I am facing an issue while attempting to send an email using sendgrid. Whenever I execute the function, it gives me an error saying "Can't find variable: require". Despite my efforts to search for a solution online, I have not been able to resolve thi ...

Utilizing jQuery.ajax() to retrieve the child div from a separate page

Can anyone help me figure out how to use jQuery ajax() to load two children contents from an external page? I want a pre-loader to display before the main content loads. Below is the code snippet that I have tried. $.ajax({ url: 'notification.htm ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Locate the position of an item in an array based on a certain value assigned to a particular

I am trying to locate the index number of a specific item within my object. Here is the object in question: [ { "type": "Grayscale", "mode": "average" }, { "type": "Sepia" }, { "type": "Invert", "invert": true }, { "type": ...

jQuery .attr malfunctioning, retrieving incorrect links

I'm currently in the process of working on this page for a project $(function() { $(".modal-launcher, #modal-background").click(function() { $(".modal-content, #modal-background").toggleClass("active"); $(".vid-1i").attr("src", "l ...

Tips for saving an array of objects in local storage and transferring it from one file to another

Recently delving into the world of localstorage, I've encountered an issue while attempting to store JSON data in one file and retrieve it in another. The JSON data below was fetched from a URL, and my goal is to obtain all the feed objects in the oth ...

The integration between Mongoose and GraphQL does not support populating models

It seems like I have encountered a unique issue that none of the existing solutions have been able to resolve. I am running a backend server with Apollo Server + Mongoose on localhost. However, I am facing difficulties in populating or creating the collect ...

Revamping and Refreshing JSON-driven Pointers

My website features a jQuery code that displays live .JSON files from an ADS-B receiver with plane lat/long information. I have successfully turned them into markers, but they only update when the page is refreshed. Despite trying setInterval and conduct ...

Is it possible that the triangulation library functions on Firefox, but encounters compatibility issues on Chrome?

Currently, I am implementing triangulation using the Poly2Tri library. This is my code: var swctx = new poly2tri.SweepContext(contour); swctx.triangulate(); var triangles = swctx.getTriangles(); for (var w = 0; w < triangles.length; w++) { pts_t ...

Transferring an array of objects between routes

I am currently working with Node.js and Express.js, attempting to pass an array of objects from one route to another. I initially attempted passing it through the QueryString, but encountered issues with the typeof identifying it as an object rather than f ...

methods for transferring information from a website to a smartphone using SMS

I am currently in the early stages of learning JavaScript and working on a project that involves creating a form (a web page) to send data to my mobile device via SMS when the submit button is clicked. However, I am unsure how to transfer data from JavaS ...