Changing the location of an ArcGIS map with a click event in a Vue application

I am attempting to dynamically update a map to display my current location using Vue. I have created an onClick event that updates the props and sends them to my map component. To trigger a re-render of the map component when the data changes, I am utilizing a :key. However, based on the esri/arcgis example, it seems like I may need to rebuild the map completely. If anyone has insight into whether this approach is incorrect, please let me know.

For reference, here is the starting documentation for using ArcGIS with VUE js:

I have encountered an issue where the map appears to render again but then remains blank. Could this be due to some persistence of the component after forcing it to render?

Below is the code snippet from my app.vue:

<template>
    <div id="app">
        <web-map v-bind:centerX="lat" v-bind:centerY="long" ref="mapRef"/>

        <div class="center">
          <b-button class="btn-block" @click="getLocation" variant="primary">My Location</b-button>
        </div>
    </div>


</template>

<script>
import WebMap from './components/webmap.vue';

export default {
    name: 'App',
    components: { WebMap }, 
    data(){
      return{
        lat: -118,
        long: 34,
      }
    },
    methods:{

      showPos(pos){
        this.lat = pos.coords.latitude
        this.long = pos.coords.longitude

        this.$refs.mapRef.updateCoordinates()
        console.log('new location',this.lat,this.long, this.$refs)   
      },


      getLocation(){
        if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(this.showPos);
          } else { 
            console.log("Geolocation is not supported by this browser.");
          }
      },

    },
};
</script>

Here is the corresponding code snippet from my map component:

<template>
  <div></div>
</template>

<script>
import { loadModules } from 'esri-loader';

export default {
  name: 'web-map',
  props:['centerX', 'centerY'],
  data: function(){
    return{
      X: this.centerX,
      Y: this.centerY,
      view: null
    }
  },
  mounted() {
    console.log('new data',this.X,this.Y)

    // lazy load the required ArcGIS API for JavaScript modules and CSS
    loadModules(['esri/Map', 'esri/views/MapView'], { css: true })
    .then(([ArcGISMap, MapView]) => {
      const map = new ArcGISMap({
        basemap: 'topo-vector'
      });

      this.view = new MapView({
        container: this.$el,
        map: map,
        center: [this.X,this.Y],   ///USE PROPS HERE FOR NEW CENTER
        zoom: 8
      });
    });
  },
  beforeDestroy() {
    if (this.view) {
      // destroy the map view
      this.view.container = null;
    }
  },
  methods:{
    updateCoordinates(){
        this.view.centerAt([this.X,this.Y])
      }
  }

};

</script>

Answer №1

It seems the key being passed as a prop to web-map may not be necessary as it's not utilized within the component.

An alternative approach could be to forcefully update the component like so:

<web-map v-bind:centerX="lat" v-bind:centerY="long" ref="mapRef" />
this.refs.mapRef.$forceUpdate()

This method ensures the entire component is updated forcibly. However, there might be a more efficient solution available. Rather than re-rendering the complete component, which would require recreating the map, you could keep the component active and trigger an event to update the coordinates instead.

According to the documentation at , you can relocate the map's center using the centerAt function.

In this scenario, the map component could feature a method such as:

updateCoordinates(coord){
  this.view.centerAt(coord)
}

You can then invoke this method from the parent component with:

this.refs.mapRef.updateCoordinates(newCenter)

I hope this information proves helpful. Please let me know if you make any progress!

Answer №2

In my opinion, you could experiment with using the Watch function in conjunction with setInterVal() to create a continuous loop that checks your location every second.

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

Using Three.js, generate a series of meshes that combine to create a seamless 90-degree donut shape

I'm on a quest to discover an algorithm that can create the following shape in Three.js. Here is my rough sketch of the expected shape The number of meshes needed to form the 90 degree donut, as well as the thickness and spacing between them, should a ...

Sending a post request from JavaScript to Django Rest Framework

I am working with a DFR api endpoint: url = http://example.com/api/data/ The URL of the page where I am running JavaScript code is: http://example.com/page/1/ I have logged in as User1 in my browser. POST request - from DRF browser API - successful. G ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

Unusual output from the new Date() function: it displays the upcoming month

Your assistance and explanation are greatly appreciated. I have created a method that is supposed to return all the days of a given month by using two parameters- the year and the month: private _getDaysOfMonth(year: number, month: number): Array<Date& ...

Position items within the dynamically generated div without appending them

Utilizing JavaScript, I dynamically generate a line but struggle to position two balls at both the 1/3 mark from the beginning and end. For reference, please view the image below. I aim to have two balls appear upon pressing enter in the input box. Despite ...

Redirecting to the homepage with ScrollTop feature

With the development of my Single page HTML5 web application, I have encountered a scrolling issue. To scroll to the top of the page, I am implementing the following code: $('html, body').animate({ scrollTop: 0 }, 800); This functionality works ...

Troubles with Promise.all and json() in JavaScript causing errors being logged as "invalid function"

I'm experiencing some difficulties with the "Promise.all" method. Essentially, I have an array of URLs (here is a simple one if you want to test it: const urlArray = [ "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299&qu ...

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

Pressing the button on the form has no effect

I am testing a login screen using NodeJS, but I am facing an issue where the submit button does not redirect to the dashboard screen as intended. What could be missing in the code? The submit button should direct to the dashboard screen that I have created ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...

The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript: var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800 ...

Issue with Material UI Textfield functionality on mobile Safari browser

UPDATE: Resolved the problem by including this code in index.css input { -webkit-user-select:text;} In my application, I am using a Material UI box that contains text fields with an onChange handler. While the TextFields function correctly on most bro ...

The international telephone input library's "grunt img" command is malfunctioning

I am currently utilizing intl-tel-input to develop a control for displaying mobile numbers. Since the flags are quite small, I am in need of enlarging them. A reference for this can be found here: https://codepen.io/jackocnr/full/ONXWgQ To achieve this, ...

Error message "The camera provided is invalid and not an instance of THREE.Camera" appears when attempting to render a cube using Three.js

I've been working on a small "engine" project using three.js to easily create and position objects. So far, I have set up the scene, renderer, and camera successfully. However, when attempting to render and attach a cube to my scene, I encounter an is ...

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

Create a Discord.js bot that automatically deletes any URLs that are posted in the server

Seeking advice on how to have my bot delete any URLs posted by members. I am unsure of how to accurately detect when a URL has been shared, especially since they can begin with https, www, or some other format entirely. Any insights would be greatly apprec ...

Utilizing promise values within asynchronous functions

I know this question has been asked multiple times, but I'm facing a situation where I need to retrieve a variable created within a promise. The examples I've come across involve using .then to access the data, but in my case, I need to work with ...

What is the process to designate a specific value to a key in an array?

I need assistance in updating the description array within the schema by adding the about and link values, followed by using the .save() function to store it in the database. Any guidance on this issue would be greatly appreciated. Thank you for your help. ...