Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to track Users Registration location in Google Maps

In this article, we will discuss the different components of HTML 5 Geo-Location API, and will connect to the database to save and fetch user location data with PHP.

HTML is a markup language that is needed to structuring and presenting content to the WWW (World Wide Web). The latest version of this markup language has been published on 28th of October by the World Wide Web Consortium (W3C). It is the fifth version hence it’s been called HTML5. HTML 5 has many special syntactic features. These include many elements, but the most noteworthy is the application programming interface (API) named “Geo-Location”. Here, we are going to make a web app that is going to monitor user location’s longitude and latitude. After that, we are going to use PHP (server side scripting language) and MySQL (open source relational database management system) to store the data of the location of the user including user’s IP-address. Also, we are going to discuss the MySQLi extension of MySQL and its advantages and disadvantages.

HTML geo-location API compromises user location and that is why the position is not available until user approves it. Geo-location is accurate with devices that support GPS system.

Requisites

For this article we need plenty of requisites which we are:

  • Adobe Dreamweaver CS6: it’s a web development tool by Adobe, which we are going to use to make the PHP code.
  • LAMP environment: it’s a source web development platform for executing PHP projects. We will need the below items :
    • Zend Server: Zend Server will create an environment for executing PHP project. If it’s a 32 bit operating system then it will be installed in program files folder of your core drive, and if it’s a 64 bit operating system, then it will be available on the program files*86 folder.
    • PHP: PHP should be downloaded in the system, because we are going to use PHP as the server side scripting language for saving the data.
    • MySQL: MySQL should be installed on the system, as we are going to use MySQL database for manipulating data.
    • Navicat Premium: Navicat premium is a database administrator tool that we are going to use to connect to MySQL database.

Steps of execution

We are going to follow step by step approach to get the desired result. The steps that we going to execute are:

Step

Description

Creating the Zend Server environment

Here we are going to set up zend server environment for our project.

Making a database and table

We are going to create an database using Navicat Premium and going to create tables onto the following database.

Creating a registration form to save the user data

We are going to create a simple form for registering a user and saving the user details in database(including, the latitude and longitude of the user)

Creating a page to fetch the user details and show a map

Last but not the least, creating a page, where we are going to fetch the user’s details and will show a map using Google API.

Making a Database and table

We are going to use MySQL database to save the data of the user and going to fetch the data later to show the map. We are going to use Navicat Premium to create and manipulate the data of the database. Below are the steps to execute for creating a new database:

  • Open Navicat Premium.
  • Click on File > New connection > MySQL. A window named “MySQL-New Connection” window will appear.
  • At that window we are going to put details of the connection. At connection name we are going to put “local_trial”, Host name/IP address and port will be fetched automatically for the local host machine, name and password will be put as per need. After that we will click on “Test Connection”.If the connection succeeds, then it will pop up an affirmative message. After clicking at the ok button the new connection named “local_trial” will appear at the left side pan of the window.
  • After that we are going to right click at the connection and click at “open connection” option, than the connection will be activated.
  • After that we will right click at the connection and click on “New Database” option. A “New Database” window will appear. There we are going to put a database name. In this article, it has been named ‘test’. Then, click ok.
  • After that, we will double click on the test database and it will be opened. Then, we will click at the Query option from the header and a new query window will appear. At that location, we are going to put the below code:

Listing 1. Query for creating the table

CREATE TABLE `geo` 
  ( 
     `id`       INT(11) DEFAULT NULL, 
     `sdate`    DATETIME DEFAULT NULL, 
     `lat`      VARCHAR(255) DEFAULT NULL, 
     `long`     VARCHAR(255) DEFAULT NULL, 
     `ip_add`   VARCHAR(255) DEFAULT NULL, 
     `name`     VARCHAR(255) DEFAULT NULL, 
     `dob`      DATE DEFAULT NULL, 
     `state`    VARCHAR(255) DEFAULT NULL, 
     `city`     VARCHAR(255) DEFAULT NULL, 
     `phone_no` VARCHAR(255) DEFAULT NULL, 
     `zip`      VARCHAR(255) DEFAULT NULL 
  )

  • A table named geo will be created. another options is to right click on the tables’ option under the test database and select “New Table”. In that way we need to put column name and data types one by one manually.

Figure 1. Output of Listing 1: Creating database and the table

Creating a registration form to save the user data

We are going to create a form using HTML5 and JavaScript to use the geo-location API of the form but we are going to save it with “.php” extension for future purposes. Below is the code of index.php which we are going to make via Adobe Dreamweaver:

Listing 2. Index.php code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Registration Form </title>
</head>

<body>
    <h3>Registration Form </h3>
    </br>
    </br>
    <form action="insertdb.php" method="POST">
        <input type="hidden" name="txtlat" id="txtlat" required value="">
        <input type="hidden" name="txtlang" id="txtlang" required value="">
        <label>Name : </label>
        <input type="text" name="txt_name" id="txt_name" required placeholder="Please type your name here">
        </br>
        </br>
        <label>Date of Birth : </label>
        <input type="date" name="txt_dob" id="txt_dob" required placeholder="Please type your date of birth here">
        </br>
        </br>
        <label>State : </label>
        <input type="text" name="txt_state" id="txt_state" required placeholder="Please type your state here">
        </br>
        </br>
        <label>City : </label>
        <input type="text" name="txt_city" id="txt_city" required placeholder="Please type your city here">
        </br>
        </br>
        <label>Phone NO. : </label>
        <input type="text" name="txt_phno" id="txt_phno" required placeholder="Type your phone number here">
        </br>
        </br>
        <label>ZIP : </label>
        <input type="text" name="txt_zip" id="txt_zip" required placeholder="Please type your ZIP code here">
        </br>
        </br>
        <input type="submit" value="submit">
    </form>
</body>
<script src="jquery.min.js"></script>
<script src="geoloc.js"></script>

</html>

The above code is going to create a simple registration form that we are going to use to see the user’s data. This is just a user interface till now. We are going to give it functionality step by step ahead.

Figure 2. Output of Listing 2: Index page (index.php)

Note: There are several places that need to be explained in the above coding. First there is a name “insertdb.php” which is mentioned in the form action, this file we are going to create later which will save the data of the user to a table.

There are two input places which are hidden that is going to take user latitude and longitude value and pass it via the form with the other data to the insertdb.php file.

Last but not the least we used two java script file named “jquery.min.js” and “geoloc.js”. “jquery.min.js” can be downloaded from the internet, its free to use. This will handle the ajax processing related to the data that geoloc.js going to pass to the index.php (data means longitude and latitude).

Creating the geoloc.js file

The geoloc.js file is very important to get the latitude and longitude of the user, which we are going to save in the database with the additional information that the user is going to put. The geoloc.js file is going to have the functionality that will put the longitude and latitude on the hidden field of the index page form. Then, after the user clicks the submit button, the details of the form with the longitude and latitude will be saved to the database. Below is the coding of “geoloc.js” file:

Listing 3. Code of geoloc.js

$(function() {
    window.onload = getLocation;
    var geo = navigator.geolocation;

    function getLocation() {
        if (geo) {
            geo.getCurrentPosition(displayLocation);
        } else {
            alert("Oops, Geolocation API is not supported");
        }
    }

    function displayLocation(position) {
        var lat = position.coords.latitude;

        var lang = position.coords.longitude;

        document.getElementById('txtlat').value = lat;

        document.getElementById('txtlang').value = lang;
    }
});

The above java script is going to call getLocation() function after the document stops loading, the getLocation() function checks if the browser that user is using supports geo location or not, if it supports geoLocation then it will call the displayLocation() function which will get the longitude and latitude of the user’s position and saves it in two separate variables named lang and lat. Last but not the least ,

document.getElementById(‘txtlat’).value=lat;
  document.getElementById(‘txtlang’).value=lang;

searches for the id ‘txtlat’ and ‘txtlang’, and passes the value lat and lang in them. In that way when user is submitting the form, the longitude and latitude is passing itself also to the insertdb.php file to save themselves at the table.

Creating the insertdb.php file

The insertdb.php file is an important file, because it is saving the data to the database with the help of mysqli extension.

The mysqli extension or MySQL improved extension came after the MySQL system version 4.1.3, which gave advantages over many new features of later versions. It has number of benefits which include object oriented interface, support for prepared statements, support for multiple statements, enhanced debugging capabilities etc. Below is the coding of the insertdb.php file:

Listing 3. Code of geoloc.js

<?php
$con = mysqli_connect("localhost", "root", "prtech", "test");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$latitude  = $_REQUEST['txtlat'];
$longitude = $_REQUEST['txtlang'];
$name      = $_REQUEST['txt_name'];
$dob       = $_REQUEST['txt_dob'];
$state     = $_REQUEST['txt_state'];
$city      = $_REQUEST['txt_city'];
$phn       = $_REQUEST['txt_phno'];
$zip       = $_REQUEST['txt_zip'];
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_X_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if (isset($_SERVER['REMOTE_ADDR']))
    $ipaddress = $_SERVER['REMOTE_ADDR'];
else
    $ipaddress = 'UNKNOWN';
$ip     = $ipaddress;
$SLNO   = "100001";
$sqlres = "select MAX(id) from `geo`";
if ($result = mysqli_query($con, $sqlres)) {
    if ($row = mysqli_fetch_array($result)) {
        if ($row[0] != "") {
            $SLNO = $row[0] + 1;
        }
    }
    mysqli_free_result($result);
}
$now = date("Y-m-d H:i:s");
mysqli_query($con, "INSERT INTO `geo` (`id`,`sdate`,`lat`,`long`,`ip_add`,`name`,`DOB`,`state`,`city`,`phone_no`,`zip`) VALUES ('$SLNO','$now','$latitude','$longitude','$ip','$name','$dob','$state','$city','$phn','$zip')");
echo "Data Saved Successfully";
?>

At first we use the mysqli_connect() function to open a new connection with the MySQL server. Which passes the host, username, password, dbname of your desired server. Then mysqli_connect_errno() function returns the error number if any error occurs. Then we save the form data to different variables. After that, the we look for an valid IP address and saves it to a variable.

Then we create a variable named ‘$SLNO’ to save a default number and increment it by looking the hightest number at the database and increment it by 1.

Then we execute a query via mysqli_query() function with the connection string and insert the data to the respective fields. Last but not the least, after entering data to the database it will show a message that ‘Data saved successfully’

Figure 3. Output of Listing 3: insertdb.php

Seeing specific user data with the map

The data has been successfully saved to the database. Now, we are going to create a file that will fetch the location data i.e. longitude, latitude and will show us the map from where the user has done the registration. Below is the code of showlocation.php file:

Listing 4. Code of showlocation.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Show Location </title>
    <script src="jquery.min.js"></script>
</head>

<body>
    <h3>Show Location</h3>
    </br>
    </br>
    <form action="getlocation.php" method="POST">
        <label for="txtuser">User *</label>
        <select id="txtuser" name="txtuser" required>
            <option value="" selected style="display:none">Select User</option>
            <?
              $con = mysqli_connect("localhost", "root", "prtech", "test");
              if (mysqli_connect_errno()) {
                  echo "Failed to connect to MySQL: " . mysqli_connect_error();
              }
              $query  = "SELECT * from geo";
              $result = mysqli_query($con, $query);
              while ($row = mysqli_fetch_array($result)) {
                  echo "<option value=" . '"' . $row[id] . '"' . ">" . $row[name] . "</option>";
              }
              mysqli_free_result($result);
            ?>
        </select>
        <input type="submit" value="Show Location" id="Gmap" name="Gmap">
    </form>
</body>

</html>

At this page, we are creating a simple form where a combo box has been given and the combo box is fetching the existing users from the database. After selecting the user when we are clicking on the submit button, the name is passed to the “getlocation.php” file, which then shows us the map.

Figure 4. Output of Listing 4: showlocation.php

Creating the getlocation.php file

The getlocation.php file shows us the map. Below is the code of getlocation.php file:

Listing 5. Code of getlocation.php

<?
$uid = $_REQUEST['txtuser'];
$con = mysqli_connect("localhost", "root", "prtech", "test");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query  = "SELECT * from geo where id='$uid'";
$result = mysqli_query($con, $query);
if ($row = mysqli_fetch_array($result)) {
    $lat  = $row["lat"];
    $lang = $row["long"];
}
mysqli_free_result($result);
?>
    <script src="jquery.min.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

    <article></article>
    <script>
        function success(position) {
            var mapcanvas = document.createElement('div');
            mapcanvas.id = 'mapcontainer';
            mapcanvas.style.height = '400px';
            mapcanvas.style.width = '600px';
            document.querySelector('article').appendChild(mapcanvas);
            var coords = new google.maps.LatLng( < ?
                echo $lat; ? > , < ?
                echo $lang; ? > );
            var options = {
                zoom: 15,
                center: coords,
                mapTypeControl: false,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.SMALL
                },
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
            var marker = new google.maps.Marker({
                position: coords,
                map: map,
                title: "You are here!"
            });
        }
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success);
        } else {
            error('Geo Location is not supported');
        }
    </script>

The above coding first takes the user name from the showlocation.php and then it fetches the longitude and latitude regarding the name and passes it to the script at the page.

Note: The coding between the script tag first creates a div element which has the height of 600*400. After that the variable coords takes the latitude and longitude for creating a map. The google.maps.MapTypeId defines the map type. After that google.maps.Maker creates the map by taking coords.

Figure 5. Output of Listing 5: getlocation.php

Conclusion

The Geolocation API is useful for many aspects, but the most important one is that it just uses HTML as the base language and JavaScript to fetch the user data. There are plenty of complex ways to know user location but Geolocation API is the most advance one,because it takes less resource and shows accurate results. By the help of this article, one can easily integrate geolocation API in his/her web pages easily and save the Longitude and Latitude of the user. This API only works in limited browsers and the geolocation doesn’t take user data stealthily, but rather it asks the user’s permission so the browser can pass the current geographical location of the user or not. Geolocation API is a must use because of its flexibility, easy coding and wonderful results.



Founder of prTechnologies, one stop IT solution company whose motto is to create the finest software/websites for its clients.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login