DEV Community

Cover image for Vue.js + Google Maps API: Getting User Location
Raja Tamil
Raja Tamil

Posted on • Updated on

Vue.js + Google Maps API: Getting User Location

Getting user location is one of the important steps when building an app that relies on street addresses such as a food delivery app for example.

In this article, I am going to quickly cover how to get user location using HTML5 Geolocation and Google’s Geocoding API in the vue.js project.

I assume that you already know how to get up and running with vue.js project.

The folder structure should be like this:

alt text

Create a vue component called UserLocation.vue inside the component folder as well as define a route object inside the router/index.js file.

Inside UserLocation.vue component add the following code.

<template>
   <section class="ui two column centered grid">
      <div class="column">
         <form class="ui segment large form">
            <div class="field">
               <div class="ui right icon input large">
                  <input
                     type="text"
                     placeholder="Enter your address"
                     v-model="address"
                     ref="autocomplete"
                     />
                  <i class="dot circle link icon" @click="locatorButtonPressed"></i>
               </div>
            </div>
         </form>
      </div>
   </section>
</template>
Enter fullscreen mode Exit fullscreen mode

And the view would look like this.

alt text

As you can see, there is an input field with a button on the right, along with a few elements building a grid-based layout using semantic ui css framework.

I have already added a semantic ui CDN link inside the index.html file.

Also, the input filed has a v-model directive with a property value called address and the side button has a click event callback function called locatorButtonPressed.

Let’s define them.

<script>
   export default {
     data() {
       return {
         address: "",
       };
     },
     methods: {
       locatorButtonPressed() {
       },
     }
   };
</script>
Enter fullscreen mode Exit fullscreen mode

Get User Geographic Coordinates Using HTML5 Geolocation API

To get the geographic coordinates (latitude and longitude), invoke the getCurrentPosition() method on the navigator object.

locatorButtonPressed() {
   navigator.geolocation.getCurrentPosition(
      position => {
         console.log(position.coords.latitude);
         console.log(position.coords.longitude);
      },
      error => {
         console.log(error.message);
      },
   )
}
Enter fullscreen mode Exit fullscreen mode

GetCurrentPosition() method takes a couple of arguments.

The first one is the success callback function which returns an object that has coordinate data specified in a parameter called position.

The second one is the error callback function.

When getCurrentPosition() method is called, the browser will show the notification where the user can either allow (success callback function) or block (error callback function).

alt text

Pretty straightforward.

Convert coordinates to street address Using Geocoding API

Geocoding API is a part of Google Maps API, and it’s the process of converting a street address into geographic coordinates (like latitude and longitude).

But what we want is…Reverse Geocoding which is the process of converting geographic coordinates into a human-readable address.

In order to use this API, you need to obtain a key from google’s cloud platform and enable Geocoding API and Maps JavaScript API.

Let’s make an HTTP request to the Geocoding API using Axios HTTP client.

To do that, create another function called getStreetAddressFrom(lat, long) with parameters inside methods object.

async getStreetAddressFrom(lat, long) {
   try {
      var {
         data
      } = await axios.get(
         "https://maps.googleapis.com/maps/api/geocode/json?latlng=" +
         lat +
         "," +
         long +
         "&key={yourAPIKey}"
      );
      if (data.error_message) {
         console.log(data.error_message)
      } else {
         this.address = data.results[0].formatted_address;
      }
   } catch (error) {
      console.log(error.message);
   }
}
Enter fullscreen mode Exit fullscreen mode

As you can see, I use Async and Await pattern in the getStreetAddressFrom() and inside the try block, make an HTTP request to geocoding API using Axios with a couple of query parameters.

The first parameter is latlong and the value of it would be the latitude and longitude that are passed into the function and the API key.

Continue Reading...

Top comments (0)