搜狗坐标转换

项目网页中嵌入了搜狗地图,地图操作用的是搜狗坐标,手机端搜集来的是gps坐标。在实现一些功能的时候需要匹配两个坐标,需要转换。调用搜狗web api转换。

#!/usr/local/bin/python
# coding=utf-8
import os 
import re
import string
from urllib import urlopen
import time
import pgdb
import fcntl

#放到操作系统cron中,每分钟执行,如果每次时间长,会造成多进程同时处理坐标,加上文件锁,保证只有一个进程有效(锁文件后缀和当前执行文件名一致)。
fp = open('cronWork/fcntlF_'+__file__.split('/')[-1].split('.')[0],'w')
try:
  fcntl.flock(fp, fcntl.LOCK_EX| fcntl.LOCK_NB)
except IOError:
  exit()

#连接数据库,查询出需要处理的坐标
db  = pgdb.connect(database='map_prov',host='218.193.xxxxxxx',user='tcsms',password='123')
cur = db.cursor()
cur2 = db.cursor()
cur.execute("select lon,lat,id from jxgb where lat is not null and sogoux is null")
records=cur.fetchall()

count=0
for r in records:
  #通过搜狗坐标转换接口计算,获取结果
  sogouUrl = "http://api.go2map.com/engine/api/translate/json?points="+str(r[0])+","+str(r[1])+"&type=2"
  #print str(r[0])+","+str(r[1])
  cmd = '''curl --connect-timeout 10 --stderr -  "''' + sogouUrl + '''"'''
  (si, so, se) = os.popen3(cmd)
  for line in so.readlines() :
    #print line
    webdata= line
    #正则表达式匹配获取结果
    reg='''"y":([\d\.E]+),"x":([\d\.E]+)}'''

    result = re.compile(reg).findall(webdata)

    for c in result:
      if len(c)>1:
        #print c[0],c[1]
        #将搜狗坐标写入数据库
        cur2.execute("update jxgb set sogoux=%s,sogouy=%s where id=%d"%(c[1],c[0],r[2]))
        count += 1
        #处理完10条就提交,避免长时间数据库并发冲突
        if count%10==0:
          db.commit()
db.commit()
db.close()

#执行结束,即释放文件锁


 

猜你喜欢

转载自blog.csdn.net/zeeeitch/article/details/51479353