util_location.lua 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. local util_location = {}
  2. PRODUCT_KEY = "v32xEAKsGTIEQxtqgwCldp5aPlcnPs3K"
  3. local lbsLoc = require("lbsLoc")
  4. local cache = { lbs_data = { lat = 0, lng = 0 } }
  5. --- 格式化经纬度 (保留小数点后 6 位, 去除末尾的 0)
  6. -- @param value 经纬度
  7. -- @return 格式化后的经纬度
  8. local function formatCoord(value)
  9. local str = string.format("%.6f", tonumber(value) or 0)
  10. str = str:gsub("%.?0+$", "")
  11. return tonumber(str)
  12. end
  13. --- 生成地图链接
  14. -- @param lat 纬度
  15. -- @param lng 经度
  16. -- @return 地图链接 or ""
  17. local function getMapLink(lat, lng)
  18. lat, lng = lat or 0, lng or 0
  19. local map_link = ""
  20. if lat ~= 0 and lng ~= 0 then map_link = "http://apis.map.qq.com/uri/v1/marker?coord_type=1&marker=title:+;coord:" .. lat .. "," .. lng end
  21. log.debug("util_location.getMapLink", map_link)
  22. return map_link
  23. end
  24. --- lbsLoc.request 回调
  25. local function getLocCb(result, lat, lng, addr, time, locType)
  26. log.info("util_location.getLocCb", "result,lat,lng,time,locType:", result, lat, lng, time:toHex(), locType)
  27. -- 获取经纬度成功, 坐标系WGS84
  28. if result == 0 then cache.lbs_data = { lat, lng } end
  29. end
  30. --- 刷新基站信息
  31. -- @param timeout 超时时间(单位: 秒)
  32. local function refreshCellInfo(timeout)
  33. log.info("util_location.refreshCellInfo", "start")
  34. if cache.is_req_cell_info_running then
  35. log.info("util_location.refreshCellInfo", "running, wait...")
  36. else
  37. cache.is_req_cell_info_running = true
  38. mobile.reqCellInfo(timeout or 20) -- 单位: 秒
  39. end
  40. sys.waitUntil("CELL_INFO_UPDATE")
  41. cache.is_req_cell_info_running = false
  42. log.info("util_location.refreshCellInfo", "end")
  43. end
  44. --- 刷新基站定位信息
  45. -- @param timeout 超时时间(单位: 毫秒)
  46. function util_location.refresh(timeout)
  47. timeout = type(timeout) == "number" and timeout or nil
  48. sys.taskInit(function()
  49. refreshCellInfo()
  50. lbsLoc.request(getLocCb, nil, timeout, nil, "bs.air32.cn")
  51. end)
  52. end
  53. --- 获取位置信息
  54. -- @return lat
  55. -- @return lng
  56. -- @return map_link
  57. function util_location.get()
  58. local lat, lng = unpack(cache.lbs_data)
  59. lat, lng = formatCoord(lat), formatCoord(lng)
  60. return lat, lng, getMapLink(lat, lng)
  61. end
  62. sys.taskInit(refreshCellInfo)
  63. sys.subscribe("CELL_INFO_UPDATE", function() log.debug("EVENT.CELL_INFO_UPDATE") end)
  64. return util_location