Vue.js + Google Maps API: Getting User Location

Google API Vue.js

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:

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>

And the view would look like this.

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.

Get User Geographic Coordinates Using HTML5 Geolocation API

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

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).

Pretty straight forward.

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.

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.

Then, I check if there is any error sent by the API, otherwise set the formatted address to the input field.

The last step is to invoke this function inside the success call back function of the getCurretnPosition() method.

Here is the problem…yes, the API is exposed to the client so anyone can make a request. 

To prevent quota theft, you can restrict the API key by allowing only specific domains.

Go ahead and edit your key…

Which then opens this:

Under Application, Restrictions →  Add An Item and enter the website address that only wants to use this API key. 

You may get this error on the browser console:

You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started

In order to get the geocoding API to work, you must enable billing otherwise it won’t work.

Go to Google Cloud Console -> Choose the project -> Select Billing from the sidebar -> Add billing

Nice! There you have it…however, we’re not done yet.

Autocomplete

There are some edge cases where a user has to enter his/her address manually. For example, a user denies to share his/her location or HTML5 geolocation API does not support his/her browser.

Thanks to the Autocomplete library, which is part of google places library in the Maps JavaScript API.

Autocomplete will suggest addresses in a drop-down list as the user starts typing his/her address.

To get started, add the Autocomplete JavaScript API URL to the index.html.

This takes two query parameters. The first one is the library I want to use, in this case. places, as Autocomplete is a part of it. The second is the API key.

Inside UserLocation.vue component add the following code inside mounted() function.

Instantiate Autocomplete method on the places objects inside-mounted() function passing an input element using this.$refs[“autocomplete”]. 

If you run the app, you should have a drop-down menu like the screenshot below

if this is not working, make sure that you have enabled Maps JavaScript API and Places API libraries on the Google Cloud Console.

Feel free to reach out to me in the comment section below if you need help with this.

Happy coding!