Looking for a way to automatically update a map within a Vue component

My component successfully:

  • Receives a string from a sibling input component via the global Bus method in created() => works
  • Manipulates the string into lat/lng coordinates via geoDecoding() => works
  • Resolves promise result coordinates, sets data, also via geoDecoding() => works
  • Attempts to refresh showMap() with changed data after an event is fired => does not work :(

Please note that I have props (commented out) with hardcoded defaults just to check showMap() with those values, and it works.

  • I have set a debugger on showMap() and noticed that latitude and longitude are not set, even though I set them under created() when invoking geoDecoding()

I would like showMap() to refresh every time an event is fired, receiving refreshed data from this.latLong.latitude / this.latLong.longitude to correctly instantiate the map according to those new values. Currently, with this code instance, showMap() instantiates a map but remains empty because it's not receiving the lat/lng from geoDecoding().

Code:

<template>
    <div class="map-container" :id="theMap"></div>
</template>

<script>
    import { Bus } from "../main";

    export default {
        name: "GoogleMapsContainer",
        data() {
            return {
                theMap: "map-for-" + this.name,
                location: '',
                latLong: {
                    latitude: '',
                    longitude: ''
                },
            }
        },
        props: {
            name,
            // 'latitude': {
            //     type: Number,
            //     default: function () {
            //         return 39.50
            //     }
            // },
            // 'longitude': {
            //     type: Number,
            //     default: function () {
            //         return -98.35
            //     }
            // },
            // 'zoom': {
            //     type: Number,
            //     default: function () {
            //         return 4
            //     }
            // }
        },
        methods: {
            showMap() {
                debugger;
                this.map = new google.maps.Map(document.getElementById(this.theMap), {
                    center: {lat: this.latLong.latitude, lng: this.latLong.longitude},

                    zoom: this.zoom
                });
            },
            geoDecoding() {
                let geocoder = new google.maps.Geocoder();
                let theLocation = this.location;
                let latLong = this.latLong;

                    return new Promise(function (resolve, reject) {
                        geocoder.geocode({'address': (theLocation ? theLocation : 'canada')}, function (results, status) {
                            console.log(results);
                            if (status === google.maps.GeocoderStatus.OK) {
                                console.log(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                                latLong.latitude = results[0].geometry.location.lat();
                                latLong.longitude = results[0].geometry.location.lng();
                            } else {
                                reject(status);
                            }
                        });
                    });
            }
        },
        mounted() {
            //this.geoDecoding();
            this.showMap();

        },
        created() {
            this.geoDecoding();
            Bus.$on('passLocation', (input) => {
                this.location = input;
                this.geoDecoding();
            });
        },


    }
</script>

<style scoped>
    .map-container {
        width: 80vw;
        margin: 5vh auto;
        height: 50vh;
        background: fuchsia;
    }
</style>

Answer №1

For proper functionality, it is recommended to implement a watcher for the latLong property:


watch: {
  latLong: {
    handler: function(newValue, oldValue) {
      this.displayMap();
    },
    deep: true
  }
},

Answer №2

I came across a solution using Google's API code that worked well for me:

panTo(<your-lat-lng-coords>);

To integrate this into your code, I implemented it during the async call.

The function in my promise is within methods:{geoDecoding(){}}, shown below:

geoDecoding() {
    let geocoder = new google.maps.Geocoder();
    let theLocation = this.location;
    let latLong = this.latLong;
    self = this;

    let service = new google.maps.places.PlacesService(this.map);
    var erez_markers = [];

    return new Promise(function (resolve, reject) {
        geocoder.geocode({'address': theLocation}, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                console.log(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                latLong.latitude = results[0].geometry.location.lat();
                latLong.longitude = results[0].geometry.location.lng();
                this.myLatlng = new google.maps.LatLng(latLong.latitude, latLong.longitude);
                self.map.panTo(this.myLatlng);//******* this would shift map on every instantiation with new lat/lng's
            } else {
                reject(status);
            }
        });
    });
}

My state data includes default values to ensure the map displays something upon initialization:

latLong: {
    latitude: 43.6532,
    longitude: -79.3832
},
location: '',
zoom: '',

The display of the map is set globally so it can be accessed from any location. This functionality is implemented under methods:{showmap(){}}

this.map = new google.maps.Map(document.getElementById(this.theMap), {
                    center: {lat: this.latLong.latitude, lng: this.latLong.longitude},
                    zoom: this.zoom
});

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

To manipulate the array in Vue by adding and removing selected HTML elements

Sharing my code snippet: <form> <div v-for="(inputPlane, index) in inputsPlanes" :key="inputPlane.id" :id="`plane-${index}`"> <input placeholder="origin" name="data" /> < ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

The function data() is coming back as null

This is the code snippet I am working with: $.getJSON("link here", function (result) { $.each(result, function (i, value) { $('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>") ...

The json_encode() function yields an empty result

I am facing an issue with a PHP script that is supposed to parse an array using the json_encode() method, but it returns a blank output. Here is the PHP code snippet: $companies = $db->getCustomerNames(); print_r($companies) if (!empty($companies)){ $ ...

How to filter an array in Angular 4 without the need for creating a new array and then displaying the filtered results within the same

In my collection of students, I have their names paired with their academic outcomes. studentResults = [ {name: 'Adam', result : 'Passed'}, {name: 'Alan', result : 'Failed'}, {name : 'Sandy', result : &ap ...

The date format in AngularJS is not being displayed correctly according to the request

My goal is to retrieve the date in the format of dd/MM/yyyy and pass it along to my URI. However, I am encountering an issue where the date is not being passed in the requested format. Below is the snippet of my HTML code: <script type="text/ng-templat ...

Tips for securely concealing an API key during website deployment on Netlify

Recently, I created a small website using Javascript just for fun and I'm looking to deploy it to Netlify. However, I've encountered an issue with the API key that the website uses. I'm struggling to figure out how to conceal this key. Curre ...

Dealing with currency symbols in Datatables and linking external sources

I'm having trouble linking an external link to the "customer_id" field. The link should look like this: /edit-customer.php?customer_id=$customer_id (which is a link to the original customer id). I am creating a detailed page with most of the informati ...

Ensure that only a single onmouseover event is triggered when hovering over multiple elements

I want to create a simple code snippet like the one below: <span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span> However, I need to ensure that when hovering ove ...

Angular Bootstrap Popover will now automatically hide after a short period of time due to the removal of the tt_isOpen variable in ui-bootstrap-tpls-0

I recently attempted to implement the ingenious directive created by runTarm for managing angular-bootstrap-popover-hide-after-few-seconds. While using ui-bootstrap 0.11.0.js presented no issues, transitioning to ui-bootstrap-0.12.0 proved problematic as ...

Execute and showcase code without redundancies

I have been exploring a way to store JavaScript code within an object and execute specific parts of it upon the user clicking a button. Here's what I've come up with so far: var exampleCode = { test: "$('body').css('background ...

What could be causing the "length" property of undefined error when attempting to install React-Bootstrap with the command "npm i react-bootstrap"?

Currently, I am working my way through a comprehensive MERN full-stack tutorial. So far, things have been going smoothly - I used the "npx create-react-app" command to set up the react application and everything is compiling and running perfectly. Howeve ...

Creating a mapping strategy from API call to parameters in getStaticPaths

I am attempting to map parameters in Next.js within the context of getStaticPaths, but I am facing issues with it not functioning as expected. The current setup appears to be working without any problems. https://i.stack.imgur.com/LeupH.png The problem a ...

Navigating through nested arrays to access JSON objects

My attempts to retrieve the JSON data from this particular API have been unsuccessful. Every time I try to fetch the JSON, I am faced with a specific set of results as shown in the code below. const request = require('request'); var url = ' ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

An essential component of Chai assertion is the inclusion of "or"

While attempting to iterate through a list of elements, I am looking to verify that the body contains either of two values. However, the current assertion method only allows me to check for one value: expect(cellText).includes(toDateFormat); Is there a wa ...

Determining the Testing Status of a Node Package Management (NPM) Package

As someone who is new to Node.js and NPM, I have a question that may seem naive. Is there a method to determine if a package published on NPM has been tested? And if so, can this process be automated? Are there any tools or frameworks available that can va ...

Tips for seamlessly incorporating React Epub Reader into your next js project

Having some trouble integrating the react epub reader with Next Js. It's working perfectly fine with react js, but I keep encountering an error. Can you help me figure out how to integrate the epub reader with next js? Here is the error This is my ...

Creating dynamic dropdowns with Ajax and HTML on the code side

I have developed a script that generates a drop-down menu and updates the .box div with a new color and image. Below is the HTML & Java code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <div> ...

Check for input validation with jQuery when the element has a specific class

Utilizing the jQuery validation plugin for a checkout form on an ecommerce platform has proven to work excellently. However, I am in need of validating only those inputs that do not possess the class no-validate. Would it be possible to make use of the de ...