Get precise Android GPS-Location in Python












2















I try to obtain the GPS-Location of my Android Phone in Python (using QPython3 app). This kind of works, but it seems there are several LocationProviders in Android:





  • gps: pure gps location, slow, energy consuming, but very accurate,
    and exactly what I need.


  • network: mix of gps and wifi/cell locating, faster, but less accurate


  • passive: like above but completely without using gps


Problem:
When I run my script (below) I only get my location provided by "network"
wich is not accurate enough.



But I can't find a way to force a specific LocationProvider.



Code:



# import needed modules
import android
import time
import sys, select, os #for loop exit

#Initiate android-module
droid = android.Android()

#notify me
droid.makeToast("fetching GPS data")

print("start gps-sensor...")
droid.startLocating()

while True:
#exit loop hook
if sys.stdin in select.select([sys.stdin], , , 0)[0]:
line = input()
print("exit endless loop...")
break

#wait for location-event
event = droid.eventWaitFor('location',10000).result
if event['name'] == "location":
try:
#try to get gps location data
timestamp = repr(event['data']['gps']['time'])
longitude = repr(event['data']['gps']['longitude'])
latitude = repr(event['data']['gps']['latitude'])
altitude = repr(event['data']['gps']['altitude'])
speed = repr(event['data']['gps']['speed'])
accuracy = repr(event['data']['gps']['accuracy'])
loctype = "gps"
except KeyError:
#if no gps data, get the network location instead (inaccurate)
timestamp = repr(event['data']['network']['time'])
longitude = repr(event['data']['network']['longitude'])
latitude = repr(event['data']['network']['latitude'])
altitude = repr(event['data']['network']['altitude'])
speed = repr(event['data']['network']['speed'])
accuracy = repr(event['data']['network']['accuracy'])
loctype = "net"

data = loctype + ";" + timestamp + ";" + longitude + ";" + latitude + ";" + altitude + ";" + speed + ";" + accuracy

print(data) #logging
time.sleep(5) #wait for 5 seconds

print("stop gps-sensor...")
droid.stopLocating()


Sample Output (fake coordinates):



net;1429704519675;37.235065;-115.811117;0;0;23
net;1429704519675;37.235065;-115.811117;0;0;23
net;1429704519675;37.235065;-115.811117;0;0;23


Summarization:
How do I get a precise GPS location in Android using Python?



Thanks in advance everyone!



EDIT: already tested:




  • inside / outside

  • enabled / disabled

  • WiFi GPS enabled (before running script)










share|improve this question



























    2















    I try to obtain the GPS-Location of my Android Phone in Python (using QPython3 app). This kind of works, but it seems there are several LocationProviders in Android:





    • gps: pure gps location, slow, energy consuming, but very accurate,
      and exactly what I need.


    • network: mix of gps and wifi/cell locating, faster, but less accurate


    • passive: like above but completely without using gps


    Problem:
    When I run my script (below) I only get my location provided by "network"
    wich is not accurate enough.



    But I can't find a way to force a specific LocationProvider.



    Code:



    # import needed modules
    import android
    import time
    import sys, select, os #for loop exit

    #Initiate android-module
    droid = android.Android()

    #notify me
    droid.makeToast("fetching GPS data")

    print("start gps-sensor...")
    droid.startLocating()

    while True:
    #exit loop hook
    if sys.stdin in select.select([sys.stdin], , , 0)[0]:
    line = input()
    print("exit endless loop...")
    break

    #wait for location-event
    event = droid.eventWaitFor('location',10000).result
    if event['name'] == "location":
    try:
    #try to get gps location data
    timestamp = repr(event['data']['gps']['time'])
    longitude = repr(event['data']['gps']['longitude'])
    latitude = repr(event['data']['gps']['latitude'])
    altitude = repr(event['data']['gps']['altitude'])
    speed = repr(event['data']['gps']['speed'])
    accuracy = repr(event['data']['gps']['accuracy'])
    loctype = "gps"
    except KeyError:
    #if no gps data, get the network location instead (inaccurate)
    timestamp = repr(event['data']['network']['time'])
    longitude = repr(event['data']['network']['longitude'])
    latitude = repr(event['data']['network']['latitude'])
    altitude = repr(event['data']['network']['altitude'])
    speed = repr(event['data']['network']['speed'])
    accuracy = repr(event['data']['network']['accuracy'])
    loctype = "net"

    data = loctype + ";" + timestamp + ";" + longitude + ";" + latitude + ";" + altitude + ";" + speed + ";" + accuracy

    print(data) #logging
    time.sleep(5) #wait for 5 seconds

    print("stop gps-sensor...")
    droid.stopLocating()


    Sample Output (fake coordinates):



    net;1429704519675;37.235065;-115.811117;0;0;23
    net;1429704519675;37.235065;-115.811117;0;0;23
    net;1429704519675;37.235065;-115.811117;0;0;23


    Summarization:
    How do I get a precise GPS location in Android using Python?



    Thanks in advance everyone!



    EDIT: already tested:




    • inside / outside

    • enabled / disabled

    • WiFi GPS enabled (before running script)










    share|improve this question

























      2












      2








      2


      3






      I try to obtain the GPS-Location of my Android Phone in Python (using QPython3 app). This kind of works, but it seems there are several LocationProviders in Android:





      • gps: pure gps location, slow, energy consuming, but very accurate,
        and exactly what I need.


      • network: mix of gps and wifi/cell locating, faster, but less accurate


      • passive: like above but completely without using gps


      Problem:
      When I run my script (below) I only get my location provided by "network"
      wich is not accurate enough.



      But I can't find a way to force a specific LocationProvider.



      Code:



      # import needed modules
      import android
      import time
      import sys, select, os #for loop exit

      #Initiate android-module
      droid = android.Android()

      #notify me
      droid.makeToast("fetching GPS data")

      print("start gps-sensor...")
      droid.startLocating()

      while True:
      #exit loop hook
      if sys.stdin in select.select([sys.stdin], , , 0)[0]:
      line = input()
      print("exit endless loop...")
      break

      #wait for location-event
      event = droid.eventWaitFor('location',10000).result
      if event['name'] == "location":
      try:
      #try to get gps location data
      timestamp = repr(event['data']['gps']['time'])
      longitude = repr(event['data']['gps']['longitude'])
      latitude = repr(event['data']['gps']['latitude'])
      altitude = repr(event['data']['gps']['altitude'])
      speed = repr(event['data']['gps']['speed'])
      accuracy = repr(event['data']['gps']['accuracy'])
      loctype = "gps"
      except KeyError:
      #if no gps data, get the network location instead (inaccurate)
      timestamp = repr(event['data']['network']['time'])
      longitude = repr(event['data']['network']['longitude'])
      latitude = repr(event['data']['network']['latitude'])
      altitude = repr(event['data']['network']['altitude'])
      speed = repr(event['data']['network']['speed'])
      accuracy = repr(event['data']['network']['accuracy'])
      loctype = "net"

      data = loctype + ";" + timestamp + ";" + longitude + ";" + latitude + ";" + altitude + ";" + speed + ";" + accuracy

      print(data) #logging
      time.sleep(5) #wait for 5 seconds

      print("stop gps-sensor...")
      droid.stopLocating()


      Sample Output (fake coordinates):



      net;1429704519675;37.235065;-115.811117;0;0;23
      net;1429704519675;37.235065;-115.811117;0;0;23
      net;1429704519675;37.235065;-115.811117;0;0;23


      Summarization:
      How do I get a precise GPS location in Android using Python?



      Thanks in advance everyone!



      EDIT: already tested:




      • inside / outside

      • enabled / disabled

      • WiFi GPS enabled (before running script)










      share|improve this question














      I try to obtain the GPS-Location of my Android Phone in Python (using QPython3 app). This kind of works, but it seems there are several LocationProviders in Android:





      • gps: pure gps location, slow, energy consuming, but very accurate,
        and exactly what I need.


      • network: mix of gps and wifi/cell locating, faster, but less accurate


      • passive: like above but completely without using gps


      Problem:
      When I run my script (below) I only get my location provided by "network"
      wich is not accurate enough.



      But I can't find a way to force a specific LocationProvider.



      Code:



      # import needed modules
      import android
      import time
      import sys, select, os #for loop exit

      #Initiate android-module
      droid = android.Android()

      #notify me
      droid.makeToast("fetching GPS data")

      print("start gps-sensor...")
      droid.startLocating()

      while True:
      #exit loop hook
      if sys.stdin in select.select([sys.stdin], , , 0)[0]:
      line = input()
      print("exit endless loop...")
      break

      #wait for location-event
      event = droid.eventWaitFor('location',10000).result
      if event['name'] == "location":
      try:
      #try to get gps location data
      timestamp = repr(event['data']['gps']['time'])
      longitude = repr(event['data']['gps']['longitude'])
      latitude = repr(event['data']['gps']['latitude'])
      altitude = repr(event['data']['gps']['altitude'])
      speed = repr(event['data']['gps']['speed'])
      accuracy = repr(event['data']['gps']['accuracy'])
      loctype = "gps"
      except KeyError:
      #if no gps data, get the network location instead (inaccurate)
      timestamp = repr(event['data']['network']['time'])
      longitude = repr(event['data']['network']['longitude'])
      latitude = repr(event['data']['network']['latitude'])
      altitude = repr(event['data']['network']['altitude'])
      speed = repr(event['data']['network']['speed'])
      accuracy = repr(event['data']['network']['accuracy'])
      loctype = "net"

      data = loctype + ";" + timestamp + ";" + longitude + ";" + latitude + ";" + altitude + ";" + speed + ";" + accuracy

      print(data) #logging
      time.sleep(5) #wait for 5 seconds

      print("stop gps-sensor...")
      droid.stopLocating()


      Sample Output (fake coordinates):



      net;1429704519675;37.235065;-115.811117;0;0;23
      net;1429704519675;37.235065;-115.811117;0;0;23
      net;1429704519675;37.235065;-115.811117;0;0;23


      Summarization:
      How do I get a precise GPS location in Android using Python?



      Thanks in advance everyone!



      EDIT: already tested:




      • inside / outside

      • enabled / disabled

      • WiFi GPS enabled (before running script)







      android python gps location-provider






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 22 '15 at 12:21









      GosuSanGosuSan

      34119




      34119
























          2 Answers
          2






          active

          oldest

          votes


















          0














          I had the same problem. You Can do something Like this if you want to enforce GPS as LocationProvider



          import android, time
          droid = android.Android()
          droid.startLocating()
          print('reading GPS ...')
          event=droid.eventWaitFor('location', 10000)
          while 1:
          try :
          provider = event.result['data']['gps']['provider']
          if provider == 'gps':
          lat = str(event['data']['gps']['latitude'])
          lng = str(event['data']['gps']['longitude'])
          latlng = 'lat: ' + lat + ' lng: ' + lng
          print(latlng)
          break
          else: continue
          except KeyError:
          continue





          share|improve this answer
























          • how to import android ?

            – arun pal
            Jul 17 '16 at 3:16



















          0














          I was trying to do something like this today and I had a similar problem. I was getting the same output over and over again. Long story short, I discovered this. Putting this in at the bottom of the loop should solve the problem.



          droid.eventClearBuffer()



          If you look at the original post sample output, you will notice that the time stamps are all the same. Clearing the buffer resets the object returned by the 'location' event.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29797435%2fget-precise-android-gps-location-in-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I had the same problem. You Can do something Like this if you want to enforce GPS as LocationProvider



            import android, time
            droid = android.Android()
            droid.startLocating()
            print('reading GPS ...')
            event=droid.eventWaitFor('location', 10000)
            while 1:
            try :
            provider = event.result['data']['gps']['provider']
            if provider == 'gps':
            lat = str(event['data']['gps']['latitude'])
            lng = str(event['data']['gps']['longitude'])
            latlng = 'lat: ' + lat + ' lng: ' + lng
            print(latlng)
            break
            else: continue
            except KeyError:
            continue





            share|improve this answer
























            • how to import android ?

              – arun pal
              Jul 17 '16 at 3:16
















            0














            I had the same problem. You Can do something Like this if you want to enforce GPS as LocationProvider



            import android, time
            droid = android.Android()
            droid.startLocating()
            print('reading GPS ...')
            event=droid.eventWaitFor('location', 10000)
            while 1:
            try :
            provider = event.result['data']['gps']['provider']
            if provider == 'gps':
            lat = str(event['data']['gps']['latitude'])
            lng = str(event['data']['gps']['longitude'])
            latlng = 'lat: ' + lat + ' lng: ' + lng
            print(latlng)
            break
            else: continue
            except KeyError:
            continue





            share|improve this answer
























            • how to import android ?

              – arun pal
              Jul 17 '16 at 3:16














            0












            0








            0







            I had the same problem. You Can do something Like this if you want to enforce GPS as LocationProvider



            import android, time
            droid = android.Android()
            droid.startLocating()
            print('reading GPS ...')
            event=droid.eventWaitFor('location', 10000)
            while 1:
            try :
            provider = event.result['data']['gps']['provider']
            if provider == 'gps':
            lat = str(event['data']['gps']['latitude'])
            lng = str(event['data']['gps']['longitude'])
            latlng = 'lat: ' + lat + ' lng: ' + lng
            print(latlng)
            break
            else: continue
            except KeyError:
            continue





            share|improve this answer













            I had the same problem. You Can do something Like this if you want to enforce GPS as LocationProvider



            import android, time
            droid = android.Android()
            droid.startLocating()
            print('reading GPS ...')
            event=droid.eventWaitFor('location', 10000)
            while 1:
            try :
            provider = event.result['data']['gps']['provider']
            if provider == 'gps':
            lat = str(event['data']['gps']['latitude'])
            lng = str(event['data']['gps']['longitude'])
            latlng = 'lat: ' + lat + ' lng: ' + lng
            print(latlng)
            break
            else: continue
            except KeyError:
            continue






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 1 '15 at 18:14









            usrXusrX

            1




            1













            • how to import android ?

              – arun pal
              Jul 17 '16 at 3:16



















            • how to import android ?

              – arun pal
              Jul 17 '16 at 3:16

















            how to import android ?

            – arun pal
            Jul 17 '16 at 3:16





            how to import android ?

            – arun pal
            Jul 17 '16 at 3:16













            0














            I was trying to do something like this today and I had a similar problem. I was getting the same output over and over again. Long story short, I discovered this. Putting this in at the bottom of the loop should solve the problem.



            droid.eventClearBuffer()



            If you look at the original post sample output, you will notice that the time stamps are all the same. Clearing the buffer resets the object returned by the 'location' event.






            share|improve this answer




























              0














              I was trying to do something like this today and I had a similar problem. I was getting the same output over and over again. Long story short, I discovered this. Putting this in at the bottom of the loop should solve the problem.



              droid.eventClearBuffer()



              If you look at the original post sample output, you will notice that the time stamps are all the same. Clearing the buffer resets the object returned by the 'location' event.






              share|improve this answer


























                0












                0








                0







                I was trying to do something like this today and I had a similar problem. I was getting the same output over and over again. Long story short, I discovered this. Putting this in at the bottom of the loop should solve the problem.



                droid.eventClearBuffer()



                If you look at the original post sample output, you will notice that the time stamps are all the same. Clearing the buffer resets the object returned by the 'location' event.






                share|improve this answer













                I was trying to do something like this today and I had a similar problem. I was getting the same output over and over again. Long story short, I discovered this. Putting this in at the bottom of the loop should solve the problem.



                droid.eventClearBuffer()



                If you look at the original post sample output, you will notice that the time stamps are all the same. Clearing the buffer resets the object returned by the 'location' event.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 24 '17 at 23:31









                David MilitanteDavid Militante

                1




                1






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29797435%2fget-precise-android-gps-location-in-python%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Paul Cézanne

                    UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

                    Angular material date-picker (MatDatepicker) auto completes the date on focus out