Blog

How to Get Current Location in HTML 5

April 1, 2020 by Jonathan

In this tutorial, I will show you how to get the user’s current location in HTML 5. There is no need of getting any help from 3rd party location API; Instead, we will use Web API. We will also use Javascript along HTML 5 to get the current location of a user or to find where am i.

Things You Will Need:

  • Google Chrome Browser or Firefox, You can use any latest browser but this script will not work on old browsers.
  • Server for running the script. You can use Apache or any other server.

We are going to use getCurrentPosition method in our Javascript.

The following lines of code will tell you whether this browser supports Geo-location or not.

if(!navigator.geolocation)

{
alert('Your Browser does not support HTML5 Geo Location. Please Use Newer Version Browsers');
}

Here is the code which shows the Latitude and Longitude of the user.

navigator.geolocation.getCurrentPosition(success, error);
function success(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
document.getElementById("lat").value = latitude;
document.getElementById("lng").value = longitude;
document.getElementById("acc").value = accuracy;
}
function error(err){
alert('ERROR(' + err.code + '): ' + err.message);
}

where am i right now

When you execute this code, the browser will ask to allow the location access. You need to click on the Allow button to run the code or to find where am i right now.

If you are going to create a script by which a user can share his/her current location by a location link then you have to use a GET method in PHP. If you need any help HTML Geo-location script you can ask in comments.

 

 

Copyright © 2020