'GPS Module in Raspberry pi using python code

I am using Neo 6M GPS module in Raspberry pi, and try to run it using python code to process the GPS data. But as I run the code it doesn't return any results. here is the code:

 import serial
 import time
 import string
 import pynmea2

 while True:
     port="/dev/ttyAMA0"
     ser=serial.Serial(port, baudrate=9600, 
     timeout=0.5)
     dataout = pynmea2.NMEAStreamReader()
     newdata=ser.readline()

     if newdata[0:6] == "$GPGLL":
         newmsg=pynmea2.parse(newdata)
         lat=newmsg.latitude
         lng=newmsg.longitude
         gps = "Latitude=" + str(lat) + "and 
         Longitude=" + str(lng)
         print(gps)


Solution 1:[1]

import serial
import time
import string
import pynmea2

while True:
    port = "/dev/ttyAMA0"
    ser = serial.Serial(port,baudrate=9600,timeout=0.5)
    dataout = pynmea2.NMEAStreamReader()
    newdata = (ser.readline().decode("utf-8")).strip("b'rn\\")

    if newdata[0:6] == "$GPRMC":
        newmsg = pynmea2.parse(newdata)
        lat = newmsg.latitude
        lng = newmsg.longitude
        gps = ("Latitude = " + str(lat) + " and Longitude = " +str(lng))
        print(gps)
    elif newdata[0:6] == "$GPGLL":
        print("Found GPGLL record: " + newdata)
    else:
        print(newdata)

Solution 2:[2]

Your if statement is not inside the while True: loop so will never be reached.

I can't test this - but I think you want something like this:

import serial
import time
import string
import pynmea2

port="/dev/ttyAMA0"
ser=serial.Serial(port, baudrate=9600, timeout=0.5)

while True:
    newdata=ser.readline()

    if newdata[0:6] == "$GPGLL":
        newmsg=pynmea2.parse(newdata)
        lat=newmsg.latitude
        lng=newmsg.longitude
        gps = "Latitude=" + str(lat) + "and 
        Longitude=" + str(lng)
        print(gps)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ace_mbj
Solution 2 cguk70