Skip to content

Instantly share code, notes, and snippets.

@shiyazt
Created August 27, 2018 14:25
Show Gist options
  • Save shiyazt/d600918af6b01a73ad69edb7609dff7c to your computer and use it in GitHub Desktop.
Save shiyazt/d600918af6b01a73ad69edb7609dff7c to your computer and use it in GitHub Desktop.
Real Time GPS Tracking on Google maps using Raspberry Pi and Thinkspeak Cloud :: Raspberry Pi send GPS value to the Thinkspeak cloud for every 60 seconds and a javascript will fetch data from cloud and post it on Google Maps
# This File consists of API calls for the GPS Parsing Functionality.This section parse the GPS values from the GPS Module.
# pynmea2 is Python library for parsing the NMEA 0183 protocol (GPS). To get that thing : pip install pynmea2
import threading
import pynmea2
import os
class Message:
def __init__(self):
self.msg =''
# Gps Receiver thread funcion, check gps value for infinte times
def getgpsdata(serial, dmesg):
print("getgpsdata")
while True:
data = serial.readline()
if data.find('GGA') > 0:
dmesg.msg = pynmea2.parse(data)
# API to call start the GPS Receiver
def start_gps_receiver(serial, dmesg):
t2 = threading.Thread(target=getgpsdata, args=(serial, dmesg))
t2.start()
print("GPS Receiver started")
# API to fix the GPS Revceiver
def ready_gps_receiver(msg):
print("Please wait fixing GPS .....")
dmesg = msg.msg
while(dmesg.gps_qual != 1):
pass
print("GPS Fix available")
# API to get latitude from the GPS Receiver
def get_latitude(msg):
print("Getting Latitude")
dmesg = msg.msg
print("Latitude:", dmesg.latitude)
# API to get longitude from the GPS Receiver
def get_longitude(msg):
print("Getting Longitude")
dmesg = msg.msg
print("Longitude:", dmesg.longitude)
# API to get Number of Satellites from the GPS Receiver
def get_num_satellite(msg):
print("Getting Number of satellite")
dmesg = msg.msg
print("No of satellites:", dmesg.num_sats)
# API to get Altitude of Antenna from the GPS Receiver
def get_altitude(msg):
print("Getting altitude of Antenna")
dmesg = msg.msg
print("Altitude (M):", dmesg.altitude)
# API to check the status of GPS Fix
def get_gps_fix(msg):
dmesg = msg.msg
print("GPS Fix stats:", dmesg.gps_qual)
# API to Exit
def function_exit(msg):
print("Exiting ......")
print("stopping the thread")
exit()
return 1
# This File will upload the GPS cordinates (ie, Lat and Long) to the Thingspeak IoT Platform
# Provide your Thingspeak Write API key in the section provided below
# pynmea2 is Python library for parsing the NMEA 0183 protocol (GPS). To get that thing : pip install pynmea2
# Run this program on Raspberry Pi
import httplib, urllib
import time,random
import threading, os, time, pynmea2
from GPS_API import *
import serial, string
ser = serial.Serial("/dev/ttyAMA0") # Select your Serial Port
ser.baudrate = 9600 # Baud rate
ser.timeout = 50
sleep = 60 # how many seconds to sleep between posts to the channel
key = '<Your Thinkspeak channel Key>' # Thingspeak Write API Key
msgdata = Message() # Creates a Message Instance
# This Function will upload Latitude and Longitude values to the Thingspeak channel
def upload_cloud():
temp = get_latitude(msgdata.msg)
temp1 = get_longitude(msgdata.msg)
params = urllib.urlencode({'field1': temp,'field2': temp1, 'key':key })
headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept" : "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print("Lat:",temp)
print("Long:",temp1)
print response.status, response.reason
data = response.read()
conn.close()
except:
print "connection failed"
if __name__ == "__main__":
start_gps_receiver(ser, msgdata)
print(msgdata.msg)
time.sleep(2)
ready_gps_receiver(msgdata)
while True:
upload_cloud()
time.sleep(sleep)
<! Reference : https://github.com/vikkey321/Display-Thingspeak-GPS-data-on-Google-Map-from-ESP12E-and-Neo-6M-GPS/blob/master/index.html >
<! Replace your THINSPEAK CHANNEL ID, THINSPEAK READ API KEY and GOOGLE MAPS API KEY >
<!DOCTYPE html>
<html>
<head>
<title>shiyaztech</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_Google_MAPS_API_KEY"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var map;
var x;
function loadmaps(){
$.getJSON("https://api.thingspeak.com/channels/THINKSPEAK_CHANNEL_ID/fields/1/last.json?api_key=THINKSPEAK_API_KEY", function(result){
var m = result;
x=Number(m.field1);
//alert(x);
});
$.getJSON("https://api.thingspeak.com/channels/THINKSPEAK_CHANNEL_ID/fields/2/last.json?api_key=THINKSPEAK_API_KEY", function(result){
var m = result;
y=Number(m.field2);
}).done(function() {
initialize();
});
}
window.setInterval(function(){
loadmaps();
}, 9000);
function initialize() {
//alert(y);
var mapOptions = {
zoom: 18,
center: {lat: x, lng: y}
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var marker = new google.maps.Marker({
position: {lat: x, lng: y},
map: map
});
var infowindow = new google.maps.InfoWindow({
content: '<p>Marker Location:' + marker.getPosition() + '</p>'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
@Acees
Copy link

Acees commented Mar 12, 2019

Hello @BogartPoe Did you solve your problem? I encountered the same error as yours. If you have solved this kindly post your solution here. Thanks!

@dextersiah
Copy link

dextersiah commented Jan 28, 2020

For those that are still trying this codes and are getting errors, i have updated his codes here https://gist.github.com/dextersiah/68949d78fff5e6a03c6be575f9882e2a

@dawidjar97
Copy link

For those that are still trying this codes and are getting errors, i have updated his codes here https://gist.github.com/dextersiah/68949d78fff5e6a03c6be575f9882e2a

Link doesn't work

@dextersiah
Copy link

dextersiah commented May 27, 2020

U can get it here here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment