Created
October 7, 2023 14:25
-
-
Save xyuanmu/30b1ce78c8373079e28a830c7ae56fc8 to your computer and use it in GitHub Desktop.
Python 通过 Windows API 获取当前设备的经纬度以及精度
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess as sp | |
import re | |
accuracy = 3 #Starting desired accuracy is fine and builds at x1.5 per loop | |
def getLoc(): | |
pshellcomm = ['powershell'] | |
pshellcomm.append('add-type -assemblyname system.device; '\ | |
'$loc = new-object system.device.location.geocoordinatewatcher;'\ | |
'$loc.start(); '\ | |
'while(($loc.status -ne "Ready") -and ($loc.permission -ne "Denied")) '\ | |
'{start-sleep -milliseconds 100}; '\ | |
'$acc = %d; '\ | |
'while($loc.position.location.horizontalaccuracy -gt $acc) '\ | |
'{start-sleep -milliseconds 100; $acc = [math]::Round($acc*1.5)}; '\ | |
'$loc.position.location.latitude; '\ | |
'$loc.position.location.longitude; '\ | |
'$loc.position.location.horizontalaccuracy; '\ | |
'$loc.stop()' %(accuracy)) | |
#Remove >>> $acc = [math]::Round($acc*1.5) <<< to remove accuracy builder | |
#Once removed, try setting accuracy = 10, 20, 50, 100, 1000 to see if that affects the results | |
#Note: This code will hang if your desired accuracy is too fine for your device | |
#Note: This code will hang if you interact with the Command Prompt AT ALL | |
#Try pressing ESC or CTRL-C once if you interacted with the CMD, | |
#this might allow the process to continue | |
p = sp.Popen(pshellcomm, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.STDOUT, text=True) | |
(out, err) = p.communicate() | |
out = re.split('\n', out) | |
lat = float(out[0]) | |
long = float(out[1]) | |
radius = int(out[2]) | |
print(lat, long, radius) | |
getLoc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment