Locate the Geo-position of a visitor in JavaScript

In this post, we are going to see how to locate the position of a user who is visiting on a web page using JavaScript.

Here we are going to locate the HTML5 geolocation and JavaScript to locate the geo position of a visitor. Before we go through code let’s get some information about HTML5 Geolocation.

Get visitors country and city in PHP using Freegeoip API

Get country data by clicking on map – PHP source code

HTML5 Geolocation to get visitor geo position

HTML5 Geolocation allows the browser to find out the geographic coordinates of the current location. The geolocation API is published through the navigator.geolocation object. It will return the latitude and longitude of the user.

Geolocation locates a visitor’s position most appropriately. We are going to display the latitude and longitude of the visitor on the web page using HTML5 geolocation API and JavaScript code.

Now below is the code that detects the position and displays it on the web page:

<script type="text/javascript">
    function get_position(){
        // Check if geolocation supported by the browser
                var positionDetails = "Your position: <br/>" + "Latitude: <strong>" + location.coords.latitude + "</strong> and " + "Longitude: <strong>" + location.coords.longitude+"</strong>";
                document.getElementById("location_content").innerHTML = positionDetails;
        } else{
            document.getElementById("location_content").innerHTML = "This browser does not support HTML5 geolocation.";
    <div id="location_content"></div>
    <button type="button" onclick="get_position();">See My Position</button>

In the above code, we have first check if the navigator.geolocation object is available on the browser or not. If it is available then go with the code that displays the latitude and longitude position of the visitor on the web page. In case, the geolocation object is not supported by the browser will show our message on the web page.

I hope you find this post interesting.

How to generate a random password in JavaScript?

One response to “Locate the Geo-position of a visitor in JavaScript”

  1. Siva says:

    How to show the distance in miles for origin to destination? I have destination address. How can I show that?

Leave a Reply

Your email address will not be published. Required fields are marked *