util_location.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 and time:toHex(), locType)
  27. -- 获取经纬度成功, 坐标系WGS84
  28. if result == 0 and lat and lng then
  29. cache.lbs_data = { lat, lng }
  30. end
  31. end
  32. --- 刷新基站信息
  33. -- @param timeout 超时时间(单位: 秒)
  34. local function refreshCellInfo(timeout)
  35. log.info("util_location.refreshCellInfo", "start")
  36. if cache.is_req_cell_info_running then
  37. log.info("util_location.refreshCellInfo", "running, wait...")
  38. else
  39. cache.is_req_cell_info_running = true
  40. mobile.reqCellInfo(timeout or 20) -- 单位: 秒
  41. end
  42. sys.waitUntil("CELL_INFO_UPDATE")
  43. cache.is_req_cell_info_running = false
  44. log.info("util_location.refreshCellInfo", "end")
  45. end
  46. --- 刷新基站定位信息
  47. -- @param timeout 超时时间(单位: 毫秒)
  48. function util_location.refresh(timeout)
  49. timeout = type(timeout) == "number" and timeout or nil
  50. sys.taskInit(function()
  51. refreshCellInfo()
  52. lbsLoc.request(getLocCb, nil, timeout)
  53. end)
  54. end
  55. --- 获取位置信息
  56. -- @return lat
  57. -- @return lng
  58. -- @return map_link
  59. function util_location.get()
  60. local lat, lng = unpack(cache.lbs_data)
  61. lat, lng = formatCoord(lat), formatCoord(lng)
  62. return lat, lng, getMapLink(lat, lng)
  63. end
  64. sys.taskInit(refreshCellInfo)
  65. sys.subscribe("CELL_INFO_UPDATE", function() log.debug("EVENT.CELL_INFO_UPDATE") end)
  66. return util_location