这是我自己写的转换GPS坐标到高德坐标的python程序,你参考一下,转换之前做好数据库备份。
#!/usr/bin/python
# coding: UTF-8
# 文件名:gaode.py
import pymysql
import requests
# GPS坐标转换为高德坐标
def transform(lon,lat):
base = 'https://restapi.amap.com/v3/assistant/coordinate/convert?locations=%f,%f&coordsys=gps&output=JSON&key=de6cf58608a044b643da48377c6bdbfb' %(lon,lat)
response = requests.get(base)
answer = response.json()
return answer['status'],answer['locations']
# 将TRACCAR数据库中GPS坐标替换为高德坐标,并做标志“gaode =1”
def updatexy(rowid, lat, lon, lat_gps, lon_gps):
sql = "UPDATE tc_positions \
SET latitude = %s, \
longitude = %s, \
latitude_gps = %s, \
longitude_gps = %s, \
gaode =1 \
WHERE id = '%d' "
data = (lon, lat, lat_gps, lon_gps, rowid)
cursor.execute(sql % data)
#print(sql % data)
db.commit()
# 打开数据库连接,连接参数根据你的数据库设置
db = pymysql.connect(host="192.168.3.8", port=3307, user="traccar_user", passwd="123456", db="traccar",charset="utf8")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT latitude,longitude,latitude_gps,longitude_gps,gaode,id FROM tc_positions WHERE gaode=0 "
#try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
lat = row[0]
lon = row[1]
lat_gps = row[2]
lon_gps = row[3]
gaode = row[4]
rowid = row[5]
# 坐标转换
gd = transform(lon,lat)
# 分隔转换后的高德坐标
gdxy = gd[1].split(",")
#print(gd[0],gdxy[0],gdxy[1])
# 如果转换成功,就将GPS坐标更新为高德坐标
if gd[0] == '1':
updatexy(rowid, gdxy[0],gdxy[1],lat, lon)
# 打印结果
print(rowid,gdxy[0],gdxy[1])
#except:
# print ("Error: unable to fetch data")
# 关闭数据库连接
db.close()
|