Utilize the fitBounds feature from GoogleMaps in Vuejs for seamless integration

I've been working on getting the map boundaries to work properly, using a method in conjunction with my existing initMap and askGeolocation methods.

Despite my best efforts, I can't seem to get the bounds functionality working so that the map zoom adjusts to fit the positions of the different markers.

I attempted to create a method called useBounds and tried calling it within addMarker, but unfortunately, it didn't produce the desired outcome. I also experimented with directly handling bounds in the addMarker() function, but still no luck.

It seems like I may be having trouble properly obtaining the LatLng values of the markers to use with the bounds methods.

<template>
  <div class="main" ref="autreRef">
    <div class="google-map" v-bind:id="mapName" ref="mainMap" @click="openComponent">
    </div>
  </div>
</template>

<script>
  const GoogleMapsLoader = require('google-maps');
  GoogleMapsLoader.KEY = 'API_KEY';

  export default {
    name: 'google-map',
    props: ['name'],
    data: function() {
      return {
        mapName: this.name + "-map",
        userCoord: {},
        markers: [],
        map: null,
        bounds: null,
        infoWindow: null,
        position: {
          lat: null,
          lng: null
        }
      }
    },

    mounted: function() {
      GoogleMapsLoader.load((google) => {
        this.$store.watch(
          (state, getters) => getters.getRestaurantInfo,
          (newValue, oldValue) => {
            newValue.map((restaurant) => {
              this.addMarker({
                lat: restaurant.lat,
                lng: restaurant.long
              }, 'restaurant')
            })
          }
        )

        this.initMap();
        this.askGeolocation();
//        this.useBounds();


      });
    },
    methods: {
      initMap() {
        const element = this.$refs.mainMap
        const options = {
          center: {lat: 48.842129, lng: 2.329375},
          zoom: 18,
        }
        this.map = new google.maps.Map(element, options);
        this.infoWindow = new google.maps.InfoWindow;
      },
      askGeolocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition((position) => {
            const pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            this.userCoord = pos
            this.addMarker(this.userCoord, 'user')
            this.map.setCenter(pos);
          }, function() {
            handleLocationError(true, this.infoWindow, this.map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, this.infoWindow, this.map.getCenter());
        }
      },

//      useBounds() {
//        this.bounds = new google.maps.LatLngBounds();
//        this.bounds.extend(marker.position);
//        this.map.fitBounds(this.bounds);
//      },

      addMarker(coord, type) {
        let icon = ''
        if (type === 'user') {
          icon = 'https://img.icons8.com/color/48/000000/marker.png'
        } else {
          icon = 'https://img.icons8.com/ios/50/000000/restaurant-table.png'
        }
        console.log('j ajoute ', coord)
        const position = new google.maps.LatLng(coord.lat, coord.lng);
        const marker = new google.maps.Marker({
          position,
          map: this.map,
          icon
        });
//        this.useBounds();
        this.bounds = new google.maps.LatLngBounds();
        this.bounds.extend(marker.position);
        this.map.fitBounds(this.bounds);
        this.markers.push(marker);
      },
      removeMarker(marker) {
        marker.setMap(null)
      },
      openComponent() {
        this.$router.push('/add-restaurant/');
      }
    },
    computed: {
    }
  };
</script>

I'm looking forward to resolving the issue with the bounds and finding a way to seamlessly integrate them into the existing code using a method that is called from elsewhere. Thank you for your assistance.

Answer №1

Alert: This method might not be the best solution. Original line of code:

this.map.fitBounds(this.bounds);

Consider trying this alternative approach:

this.$nextTick(() => {
  this.map.fitBounds(this.bounds);
});

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

How can I effectively utilize find, match, and filter functions with a reactive array in VueJS?

Having some trouble with understanding .value! :) I'm currently working with VueJS v3 and the Composition API. My goal is to locate the first matching value in a reactive array of people. Typically, this array would be populated through an API call, ...

Using CasperJS, learn how to effectively utilize the jQuery find() function

I'm looking to implement something similar to Cabybara within a function in CasperJS. My goal is to select parent divs and extract text from their child elements. Here's an example of what I want: $('div.education').find('h4&apos ...

Is there a way to create a JavaScript script that automatically updates a webpage for all users simultaneously?

I have developed a web application that enables users to modify content using JavaScript. Currently, these changes are only visible on the local browser and do not involve AJAX. However, I am wondering how I can ensure that these DOM alterations are refle ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...

I have a task of initiating a request from JavaScript to a PHP file using an API

Seeking assistance! I have two php files named Data.php and Status.php. The task is to send a request to Data.php when data is entered in the zip field, and if the zip code is valid, then send the data to Status.php for parsing the response. Below you will ...

Understanding the Submission of a Form upon the submission event

On my form, I have multiple buttons - two of them use ajax to submit the form and clear it for adding multiple records, while the last button is for moving onto the next page. I'm wondering if jQuery's .submit() method can determine how the form ...

Having difficulty accurately interpreting the input value

As someone new to JavaScript, I set out to create a basic calculator using JavaScript and HTML. My goal is to have two input fields, named Fld1 and Fld2, that would add up the values entered into them when submitting. However, despite parsing the input val ...

The height of a DIV element can vary based on

Looking at this div structure: DIV3 has a fixed height. The nested DIV5 will be receiving content from Ajax, causing its height to change. Additionally, there are some DHTML elements inside it that also affect the height. DIV5 has a fixed min-height set. ...

Generating a JSON document from a collection of text files

I have a question about JSON files and bash scripting: My goal is to create a JSON file that contains two keys, "key1" and "key2", each with multiple values stored in separate .txt files. The contents of the .txt files for each key are structured like thi ...

Ways to verify checkbox with vuelidate?

I recently built a registration form using nuxt which includes a checkbox. I am now looking to implement validation for this checkbox. My current approach involves utilizing the vuelidate plugin. <div> <div class="form-group"> ...

"Before the click even happens, the jquery click event is already

As I was developing a small todo app, I ran into an issue where the alert message seemed to pop up before the click event was triggered. It almost seems like the event is not registered properly. Can someone explain why this is happening? (function() { ...

How to use jQuery to target the second or any desired div element with a specific class

I'm having trouble with something seemingly simple Let's say we are looking for a class called .contentdiv, for example. I am trying to target the second or nth occurrence of the .contentdiv class in a document and retrieve the HTML of that spe ...

Guide to sending multiple forms from an HTML page to another PHP page

What is the best way to submit multiple forms on a single HTML page to a PHP page and process all the form elements in PHP upon clicking one button? Any suggestions are appreciated. Thank you in advance. <form id="form1" name="form1"action="abc.php" ...

Maintain the current application state within a modal until the subsequent click using Jquery

Due to the challenges faced with drag and drop functionality on slow mobile devices, I am considering implementing a modal approach for moving elements from one place to another. Here is how it would work: When a user clicks on an item, it is visually ma ...

Creating a reusable function for making HTTP requests in Angular

I have a scenario in my controller.js where I need to make an HTTP GET request when the page loads and when the user pulls to refresh. Currently, I find myself duplicating the $http code. Is there a way to refactor this for reusability? I'm struggling ...

"Exploring the World Wide Web with JavaScript and Ajax in Internet

Is there a way to include a Javascript snippet at the end of some ajax content? It seems to be functioning properly in Firefox, but when I try it in Internet Explorer, the script is printed out without being executed. <script type="text/javascript"&g ...

JavaScript counter that keeps updating without pause

How can I create a live and continuous number counter on my website? After seeing the question above, I am interested in implementing a similar feature but with a slight twist. I am looking to have a counter that increments by 15.8 cents per second start ...

Discover the Elements that have been incorporated through the use of JavaScript

I am facing an issue with my ASP site where users can add Label elements. The problem is I am not able to track the labels that were added or their IDs. All I know is that they will be inside the Panel called pnl_Added. Once the user has finished adding la ...

Run audio player in the background with Google Chrome Extension

I am working on an extension and I want to have a page with an audio player that continues to play even when I click outside of the extension. I tried using the "background" attribute in the manifest file, but it seems to only work with javascript files. ...

Achieve Dual Functionality with Vue.JS Button within a Parent Element

My parent component structure looks like this: <template> <b-container> <b-modal id="uw-qb-add-item-modal" ref="uw-qb-add-item-modal" title="Enter Item Number" @ok="handleNewItem"> <f ...