Step by step guide on connecting data values to the Google Maps API

Recently, I've been working on geocoding within my Vue application by utilizing the Google Maps API. Within the API documentation, they provide various methods for obtaining coordinates based on addresses. For example:

https://maps.googleapis.com/maps/api/geocode/json?address=Washington&key=YOUR_API_KEY

But what if I want to use an address that is already stored in my application? Currently, I have fields displaying street, street number, zip code, and city - all retrieved from my own database. Is there a way to connect these fields with the API?

<template>
  <b-form-row v-else class="col-md-12 m-0 p-0">
    <input label="street" v-model="addressInfo.streetName" @input="emitUpdateEvent" icon="fas fa-road"
                  class="col-md-4"/>
    <input label="numberAbbr" v-model="addressInfo.streetNumber" @input="emitUpdateEvent" icon="fas fa-hashtag"
                  class="col-md-2"/>
    <input label="floor" v-model="addressInfo.floor" @input="emitUpdateEvent" icon="fas fa-layer-group"
                  class="col-md-2"/>
    <input label="door" v-model="addressInfo.door" @input="emitUpdateEvent" icon="fas fa-door-closed"
                  class="col-md-2"/>
    <input label="placeName" v-model="addressInfo.placeName" @input="emitUpdateEvent" icon="fas fa-road"
                  class="col-md-4"/>
    <input label="postalCode" v-model="addressInfo.postalCode" @input="updatePostalCode" icon="fas fa-city"
                  class="col-md-2"/>
    <input label="city" v-model="addressInfo.city" @input="emitUpdateEvent" icon="fas fa-city" class="col-md-3"/>
  </b-form-row>
</template>

I would like to achieve something along the lines of:

https://maps.googleapis.com/maps/api/geocode/json?{ addressInfo.streetName + addressInfo.streetNumber + addressInfo.zipCode + addressInfo.postalCode etc. }&key=YOUR_API_KEY

Furthermore, I have created a field labeled "coordinates" where I'm storing this data.

  getGeoLocationForUnit() {
    axios.get('https://maps.googleapis.com/maps/api/geocode/json?address=Washington&key=mykey')
      .then(result => {
        this.coordinates = result.data
      })
      .catch(error => console.error(error));
  }

Answer №1

Have you attempted a similar approach? Consider adding the dump address with a comma, if successful, you can then create a computed map data property.

axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=Washington,Street,Number&key=mykey`)

For example:

computed: {
 getFullAddress() {
  return this.addressInfo.streetName + ',' + this.addressInfo.streetNumber + ',' + this.addressInfo.zipCode + ',' + this.addressInfo.postalCode;
 }
}

Try something like this:

axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=` + this.getFullAddress + `&key=mykey`)

Answer №2

retrieveLocationData() {
    const address = `${this.addressInfo.streetName} ${this.addressInfo.streetNumber} and so on..`;
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=mykey`)
      .then(response => {
        this.coordinates = response.data
      })
      .catch(err => console.error(err));
  }

Answer №3

Have you heard of template literal strings? These are strings enclosed in backticks instead of quotes. Here's a simple example:

const name = 'John Smith';

const greeting = `Hello ${name}` // Outputs 'Hello John Smith'

In your scenario, you can even split the creation of address information string into a separate computed property, making it more organized:

data: () => ({
  baseApiUrl: 'https://maps.googleapis.com/maps/api/geocode/json?',
}),
computed: {
  addressString() {
    const { streetName, streetNumber, zipCode, postalCode } = this.addressInfo
    return `${streetName} ${streetNumber}, ${zipCode} ${postalCode}`
  }
},
methods: {
  getGeoLocationForUnit() {
    const url = `${baseApiUrl}${addressString}&key=mykey`;
    axios.get(url)
      .then(result => {
        this.coordinates = result.data
      })
      .catch(error => console.error(error));
  }
},

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

Javascript is throwing a reference error because it can't find a definition for StringBuilder

I have a JavaScript function that utilizes a string builder function. It works smoothly in most major browsers like IE8+, Chrome, and Firefox but occasionally I encounter an error stating "stringbuilder is not defined". This issue seems to only affect cert ...

GLSL: Utilizing varying amounts of textures in the sampler2D

Is there a way to dynamically pass an array of textures to shaders through a uniform sampler2D in Three.js? In the code snippet below, I am attempting to send two textures to the shaders and initialize the uniform value texture with a length of 2. However ...

Design a button for removing the selected value in select2

Can anyone provide some guidance on using select2? I am working with 2 select2 elements, and I want the selected value to be displayed on a button instead of in the input area of the select2. This way, the select2 will still display the placeholder text. ...

Having trouble modifying the Input with split() in angularJS

I am faced with a nested JSON object that contains an array as one of its properties. Each item in the array is separated by a ';'. My goal is to use ';' as a delimiter to split each array item and make necessary changes. However, I am ...

Create an HTML table by converting a JSON array and populate the table data within td tags

I have a JSON array returned as shown below {"id":16,"minutes":146} {"id":17,"minutes":137} {"id":18,"minutes":123} {"id":22,"minutes":84} I am attempting to display the above JSON array inside table tbody td where the JSON array id's match the td i ...

The div in JavaScript is expanding properly, but it is not contracting back as expected

I'm experiencing an issue with a div element that I created. My goal is to have it expand when a link is clicked and collapse when the same link is clicked again. At the moment, the div expands correctly but does not collapse as expected. Any assistan ...

Create a unique AngularJS application

I am currently in the process of transforming a pre-existing app into an AngularJS application to the fullest extent possible. Our decision is to utilize AngularJS for managing all modal windows, which are currently controlled using jQuery UI Dialog. I fin ...

"Switching out elements and tallying up values in an array

I am working with an array of identifiers for items var names = ['1','2', '1', '3']; Using these ids, I send an ajax request to retrieve the name associated with each id and replace it accordingly; var names = [ ...

Obtaining the clicked element within a functional component in React

I'm having trouble in React because I am unable to select the clicked element. The use of "this" in a functional component is not functioning as expected. function Test(data) { function getElement() { } return ( <div> ...

Tips for choosing input content when there is a single error class

I'm trying to determine if there is exactly one div with an error class. If so, I want to use the .select() method to select the content of the corresponding input (within that input's parent div). Any ideas on how to achieve this? This is my a ...

Steps to create a "drop down" feature similar to the one seen in Gmail

I am currently working on creating a dropdown panel similar to the one found on the top bar of Gmail. When users click on the Setting icon, their name, or the Share link, a panel drops down. Is there a jQuery plugin available that can help me quickly imp ...

React Component Functions for Export and Import

Currently working on a webapp built with React. My main component is defined in App.js, while I have another subcomponent responsible for creating buttons, like the logout button generated by renderLogoutButton(). But now, I want to reuse this function in ...

Steps for formatting and retrieving the <style jsx> string from a function within a React or Nextjs application

In my quest to discover a method of "organizing" react components similar to Vue, where they are packaged together with separate sections for HTML, JS, and CSS. For instance export default function HeaderExample() { return ( <> ...

Arranging the Bars in a Bar Chart Using Chart.JS

Lately, I've been playing around with ChartJS and encountering an issue with sorting the bars in descending order, from lowest to highest. Despite my efforts to troubleshoot, I haven't had any success in resolving it. ...

Issue with Vanilla JS not firing the shown event in Bootstrap tabs

I am struggling to identify when a tab is displayed using Vanilla JS, but the event doesn't seem to be working. Despite researching various solutions, none of them have been helpful in resolving this issue. Here's my current code snippet. var ...

When should we utilize the React.Children API in React applications?

Exploring the potential use cases of the React.Children API. The documentation is a bit confusing for me (Using React v.15.2.0). https://facebook.github.io/react/docs/top-level-api.html#react.children According to the documentation, this.props.children ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

Unable to view Chart.js on the second tab

I'm currently working on two different charts for a project - a bar chart and a line chart. The bar chart is displayed on the first tab, while the line chart is on the second tab. Interestingly, the bar chart functions properly, and when I point the l ...

An error message regarding JavaScript: 'Attempting to access a property that is undefined'

The code for javascript, html and css can be found working smoothly in this jsfiddle However, when the same code is placed into an HTML file like below: <!doctype html> <html> <head> <meta charset="utf-8"> <met ...

Retrieve pixel information upon touch in an Appcelerator Titanium application on Android or iPhone

Can pixel level data of an image view be accessed using Titanium Mobile on Android/iPhone? ...