Dynamic zoom based on the furthest points

I am currently using OL 4.6.5.

In my project, I have markers in a vector layer and I created a custom method to determine the zoom level based on the distance between the markers. While it's not the most elegant solution, it gets the job done...

Now, I'm on the lookout for a more efficient way to automatically set the zoom level based on the maximum and minimum latitude and longitude values. I attempted to use "fitExtent()" but couldn't get it to work as expected. After some research, I came across two potential solutions, but only one of them worked:

var onChangeKey = vectorSource.on('change', function() {
    if(vectorSource.getState() == 'ready') {
        vectorSource.unByKey(onChangeKey);
        map.getView().fitExtent(vectorSource.getExtent(), map.getSize());
    }
});

This code snippet utilizes "fitExtent()" in a different manner than I had tried before, although I encountered an issue where the zoom level remained at 2. The other solution involved strange syntax that resulted in a JS console error: "Uncaught SyntaxError: Unexpected identifier".

You can view an example page demonstrating this issue here: . The JavaScript code is located at the bottom of the page, showcasing both solutions I experimented with - the one mentioned above is currently active. Additionally, you'll find my initial, less sophisticated approach present within the code.

Surely there exists a smarter solution for this problem, right?

Answer №1

The structure you included in your code is not needed in this context since

vectorSource.on('change', function() {
is only crucial when asynchronously loading a source (such as Ajax calls).

Your code runs synchronously, like so:

var vectorSource = new ol.source.Vector({
    features: [placeOSM[1], placeOSM[2]]
});
...

Swap out the following chunk:

var onChangeKey = vectorSource.on('change', function() {
  if (vectorSource.getState() == 'ready') {
    vectorSource.unByKey(onChangeKey);
    map.getView().fitExtent(vectorSource.getExtent(), map.getSize());
  }
});

with

// The method fitExtent has been changed to fit and the second argument map.getSize() is now optional
// Referring to http://openlayers.org/en/latest/apidoc/ol.View.html#fit 
map.getView().fit(vectorSource.getExtent());

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

Component not refreshing when state changes occur

I have a unique react application that resembles the one showcased in this codesandbox link https://codesandbox.io/s/eatery-v1691 By clicking on the Menu located at the bottom center of the page, it triggers the display of the MenuFilter component. The M ...

The formValidation, previously known as BootstrapValidator, is causing issues with my form submission via Ajax, despite my efforts to update the code to work with

I recently upgraded the old BootstrapValidator to the new 0.6.0 release known as formValidation. Despite reading the documentation multiple times, I have been unsuccessful in finding the issue and need some assistance. Below are the CSS styles and scripts ...

Unable to submit form using jQuery is not functioning as expected

I am attempting to trigger a function when the submit button in the form is clicked. My aim is for the page not to refresh, and instead, I want to use AJAX to add the category. The issue arises when I manually include it in the HTML file, everything works ...

HTML Code contains jQuery Tooltips but they remain hidden from view

Looking for some stylish help buttons on my website using jQuery and tooltips. Although they show up in the Element search, they are not visible on the site. Take a look at the code snippet below: <div class="card-header"> <h5 style="float ...

What is the best way to adjust image size based on different screen sizes while ensuring the buttons at the top remain responsive

How can I make the image and image select and delete buttons responsive? I am looking to eliminate the gap after the delete button. Any suggestions are welcomed. <div class="container mt-0"> <div class="row"> ...

What is the most effective way to divide data according to its unique identifier?

Currently, I am fetching data from a file and using the code below to add individual line data to results. My objective is to split the data based on the id indicated in the tag ID. The aim is to retrieve all the information related to that specific id, ev ...

An unexpected error occurred: ReferenceError - document is undefined

Error Alert: Unhandled Runtime Error ReferenceError: doc is not defined Source of Issue components\Modal.js (42:18) @ updateDoc 40 | await uploadString(imageRef, selectedFile, "data_url").then(async (snapshot) => { 41 | const do ...

"Is it possible to selectively load only a few images on a website that contains numerous

My website displays numerous images hosted on a server. Each page contains a maximum of 100 images, each within its own div element. At any given moment, only one div is visible due to the CSS "display" property, while the others are hidden using display:n ...

Is it a cause for concern that SWR reveals client-id and Bearer tokens with each API call?

After building an application using NextJs, NextAuth, and SWR, I encountered a concern. I utilize SWR to call multiple Twitch APIs, authenticating with my Twitch applications Client-Id and the user's Bearer token from the NextAuth session object. The ...

Avoiding the stacking of event listeners in React onClick when removing and re-adding the same listener

Is it possible to remove and add the same event listener in an onClick React event? The goal is to have an event listener added to the parent element when the target element is clicked, and then removed on the next click to prevent stacking. One issue tha ...

What causes Child component to re-render in this basic example of React?

After devouring countless articles on React renders and composition, I found myself in a sea of conflicting information. However, I remember a key point that stood out to me: if React still has the same children prop it received from the App last time, it ...

String includes another String not refreshing automatically

How come myCtrl.greeting doesn't automatically update when I change myCtrl.name? angular.module('MyApp', []) .controller('MainController', [function(){ var mCtrl = this; mCtrl.name = ''; mCt ...

Find the mean of three numbers stored in an array of objects

I am currently working on a school assignment that requires me to develop a function for calculating the average mark of 3 students using an existing object in an array. Below, you can see the array and function that I have been working on as part of this ...

Verify that the value being returned is in the form of a promise

Provided an angular controller containing the following function: this.checkResponse = function (response) { if (response.success === true) { return $q.resolve(response); } else { return $q.reject(response); } }; I am looking to test with J ...

Transform an array of Boolean values into a string array containing only the values that are true

Suppose we have an object like the following: likedFoods:{ pizza:true, pasta:false, steak:true, salad:false } We want to filter out the false values and convert it into a string array as shown below: compiledLikedFoods = ["pizza", "steak"] Is t ...

Function is raising an error with the wrong value or text

I am currently testing a form that I am in the process of developing. My goal is to have different values returned each time I click on a different item from the dropdown menu. If this explanation isn't clear, please take a quick look at my pen for cl ...

Why does the JavaScript code work perfectly in Mozilla, but show an unknown runtime error in IE6?

When building my page, I implemented a simple blow up trick. Initially, the div is set as hidden, and when the image is clicked, a blow up effect occurs with an overlay image in the background. The JavaScript function updates the innerHTML. While this work ...

Challenges with jQuery's 'this' selector in conjunction with if/else conditions

I am currently working on a project that involves allowing users to modify or move an image in the browser by clicking on buttons located on the side of the page. However, I am facing issues with the script in my if/else statement. Here is a snippet of wha ...

I noticed a change in the state between dispatches, but I did not make any alterations to the state

Although this question has been previously raised, most of the discussions focus on the OP directly mutating the state. I have taken precautions to avoid this by using techniques like the spread operator with objects and arrays. However, despite these effo ...

Purge the cache of CSS and JavaScript in your browser

Is there a way to clear JavaScript and CSS cache in ASP MVC without having to clear browser history? ...