util_location.lua 2.5 KB

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