Get Current Location Using HTML5 Geolocation API

Last modified on February 27th, 2021
Raja Tamil
Google Maps API Vue.js

In this tutorial, we will be talking about the HTML5 Geolocation API and how to get geographic coordinates (latitude and longitude) from it.

By the end of this tutorial, you’ll be able to:

  • Understand what HTML5 Geolocation API is and verify browser support.
  • Attach a Click Event.
  • Perform a Browser Support Check.
  • Get Latitude and Longitude using the getCurrentPosition() Method.
  • Show an Error Message when the user denies permission.

Step #1: What is HTML5 Geolocation API

HTML5 Geolocation is a browser-based API which basically allows us to get a user’s location in the form of geographic coordinates which are latitude and longitude values.

[blog-in-between-card]

Here is the chart that shows which browser and it’s version that supports this Geolocation API.

One thing worth pointing out here is that Google Chrome version 50 or above only enables this API when using an HTTPS connection. However, it works fine on a local host which is exactly where we will be testing this.

Step #2: Attach A Click Event

Let’s attach a click event to the locator button to get the user location. Add a click event handler using @click with a callback function called locatorButtonPressed to the locator icon, which is an i element.

<i class="dot circle link icon" @click="locatorButtonPressed"></i>

After the ending </template> tag, create a script element which is where all of the javascript code would go.

<script>
export default {
}
</script>

In Vue, we create all the event handler callback functions inside the methods object, which is the standard best practice.

<script>
export default {
  methods: {
       locatorButtonPressed() {
       }
  }
}
</script>

The first thing we want to do inside the function is to check if the Geolocation API is supported by the user’s browser or not.

Step #3: Browser Support Check

Inside the locatorButtonPressed callback function, check to see if the Geolocation is supported by the using navigator.geolocation object.

export default {
  methods: {
    locatorButtonPressed() {
      if (navigator.geolocation) {
        console.log("Your browser supports Geolocation API");
      } else {
        console.log("Your browser does not support Geolocation API");
      }
    }
  }
};

If the browser supports the Geolocation API, we can get the geographical coordinates using one of it’s methods, called getCurrentPosition upon the user’s permission.

Otherwise, users will still be able to type their address using the Autocomplete API.

Step #4: Get User Location Using getCurrentPosition()

The getCurrentPosition() method takes three arguments:

  • The success function – successFunc(position)
  • The error function – errorFunc(error)
  • An options object

When the getCurrentPosition is called, a browser notification window will appear close to the URL bar on the browser and state, in my case, “the local host wants to know your location.”

If the Allow button is pressed the getCurrentPosition method will return the coordinate object to the success function specified in the parameter called position.

On the other hand, when the Block button is pressed, the error function will be invoked and will return the object specified in the error parameter.

Inside the if block, invoke the getCurrentPosition method and semicolon.

In between the parenthesis, declare the first argument, which is the success error function, with a parameter position in which we can get latitude and longitude coordinates. As you can see, I have console logged them in the code.

if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          position => {
           console.log(position.coords.latitude);
           console.log(position.coords.longitude);
          },
          error => {
             console.log(error.message);
          }
        );
} else {
        console.log("Your browser does not support geolocation API ");
}

Step #5: Show Error Message

Declare the second argument, which is the error arrow function, and console.log opening and closing parentheses error.message.

Save the file and switch back to the browser. Open the developer console by right-clicking the browser and select Inspect.

Click the locator button. The notification window pops up, choose Allow, and you can see the latitude and longitude coordinates are printed in the console.

Let’s see if the error message works as expected by blocking the location. Click the locator button again, and this time the notification does not show up.

Why?

This is because we already gave permission to the browser to get our location.

To reset it in chrome, click on the i icon, which is before the address bar and change the location option from allowed to ask and reload the page.

Lets try it again. This time choose the block option and you will see the error message appear in the developer console.

The next step is to convert these coordinates to an actual human-readable mailing address using Google’s Geocoding API.

FREE 1-HOUR COURSE:
Vue JS & Google Maps API

ACCESS FREE COURSE NOW