Open In App

Gps Tracker Using Python

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A GPS tracker is a device designed to calculate precise and accurate locations generally by receiving data from satellite sources and computing the exact coordinates of the desired location. To achieve this, we will utilize the requests library in Python, along with some other necessary libraries. We are also going to use folium, a Python library help us build the map that we are going to display at the end to the user.

This article covers all the steps with some necessary requirements on how we can make a GPS tracker in Python with ease. We will cover all the basic steps with clear and concise explanations.

GPS Tracker Using Python

Below is the step-by-step procedure by which we can track the user location using its IP address in Python:

Step 1: Install Necessary Libraries/Packages

In this step, we will install all the necessary packages or libraries required to create a GPS tracker in Python.

pip install folium
pip install requests
pip install selenium
pip install datetime

Step 2: Import Libraries

In this step, we will import all necessary libraries that are required in this project.

Python3




#Importing all necessary Libraies
 
import requests
from selenium import webdriver
import folium
import datetime
import time


Step 3: Creating a method to get the user coordinates.

In this step, we will be creating a user defined function to the user coordinates ( i.e. longitude and latitude). We are requesting for users Ip address info. This will return us a json file. Through this json file, we will extract user latitude, longitude, city and state.

Python3




#this method will return us our actual coordinates
#using our ip address
 
def locationCoordinates():
    try:
        response = requests.get('https://ipinfo.io')
        data = response.json()
        loc = data['loc'].split(',')
        lat, long = float(loc[0]), float(loc[1])
        city = data.get('city', 'Unknown')
        state = data.get('region', 'Unknown')
        return lat, long, city, state
        #return lat, long
    except:
        #Displaying ther error message
        print("Internet Not avialable")
        #closing the program
        exit()
        return False


Step 4: Creating the object of the necessary library

In this step we will define a method “gps_locator()” with no parameter. Then, we will create a folium map object under our created method.

Python3




def gps_locator():
 
    obj = folium.Map(location=[0, 0], zoom_start=2)


Step 5: Fetching Coordinates, City and State and Map Generation

In this step, we will fetch coordinates from our created method i.e. locationCoordinates(). From this coordinates, we will generate a map pointing to our exact location with the help of folium library. We will consider doing all this work under try block to avoid any undesirable errors.

Python3




try:
    lat,long,city,state = locationCoordinates()
    print("You Are in {},{}".format(city,state))
    print("Your latitude = {} and longitude = {}".format(lat,long))
    folium.Marker([lat,long], popup='Current Location').add_to(obj)
 
    #We have specified our folder location here
    #You should change this with your folder location
    #where you want your file
    fileName = "C:/screengfg/Location" + str(datetime.date.today()) + ".html"
 
    obj.save(fileName)
 
    return fileName
  except:
    #Displaying ther error message
    print("Internet Not avialable")
    #closing the program
    exit()
    return False


Step 6: Creation of main method and displaying the map.

In this method, we will create a a main method. Under this main method, we will call gps_locator() method. This method will return a file location. Through this file location, we will open that in our chrome browser using selenium. We are also closing our browser with 30 seconds, in case user do not close it manually.

Python3




if __name__ == "__main__":
 
    print("---------------GPS Using Python---------------\n")
     
    page = gps_locator()
    print("\nOpening File.............")
    dr = webdriver.Chrome()
    dr.get(page)
    time.sleep(30)
    dr.quit()
    print("\nBrowser Closed..............")


Complete Code Implementation

Here we have provided you the compiled code with necessary instruction in form of comments.

Python3




# Importing Necessary Modules
import requests
from selenium import webdriver
import folium
import datetime
import time
 
# this method will return us our actual coordinates
# using our ip address
 
def locationCoordinates():
    try:
        response = requests.get('https://ipinfo.io')
        data = response.json()
        loc = data['loc'].split(',')
        lat, long = float(loc[0]), float(loc[1])
        city = data.get('city', 'Unknown')
        state = data.get('region', 'Unknown')
        return lat, long, city, state
        # return lat, long
    except:
        # Displaying ther error message
        print("Internet Not avialable")
        # closing the program
        exit()
        return False
 
 
# this method will fetch our coordinates and create a html file
# of the map
def gps_locator():
 
    obj = folium.Map(location=[0, 0], zoom_start=2)
 
    try:
        lat, long, city, state = locationCoordinates()
        print("You Are in {},{}".format(city, state))
        print("Your latitude = {} and longitude = {}".format(lat, long))
        folium.Marker([lat, long], popup='Current Location').add_to(obj)
 
        fileName = "C:/screengfg/Location" + \
            str(datetime.date.today()) + ".html"
 
        obj.save(fileName)
 
        return fileName
 
    except:
        return False
 
 
# Main method
if __name__ == "__main__":
 
    print("---------------GPS Using Python---------------\n")
 
    # function Calling
    page = gps_locator()
    print("\nOpening File.............")
    dr = webdriver.Chrome()
    dr.get(page)
    time.sleep(4)
    dr.quit()
    print("\nBrowser Closed..............")


Output

GPS_final

Console Output

We can clearly see, its displaying city with the state.

Video Output

Conclusion

A GPS tracker is device is designed to calculate and display precise location generally received from satellite sources. We have made a GPS tracker in Python through fetching information from user’s ip address. We have use an API to fetch details and then calculates the exact coordinates. From this coordinates, we have get our current address and also we have created a html file of the map and displayed it in our browser with the help of selenium. It is simple to understand and it also uses some different and libraries to achieve the end task.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads