weather.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import {
  2. http,
  3. Method
  4. } from '@/utils/request.js';
  5. import storage from "@/utils/storage.js";
  6. import api from "@/config/api.js";
  7. /**
  8. * 获取当前地址天气(使用腾讯地图获取当前经纬度坐标)
  9. * @param {Object} params 查询参数
  10. * @param {number} params.latitude 纬度
  11. * @param {number} params.longitude 经度
  12. * @param {string} params.type 非必填 查询天气类型,取值:
  13. * now[默认] 实时天气预报
  14. * future 未来天气预报(默认获取当天和未来3天的天气信息)
  15. * hours 未来24小时天气预报(起始时间为当前时间的前一个小时)
  16. * @param {string} params.get_md 非必填 未来预报天数,仅在type=future时生效,取值:
  17. * 0 [默认]当天加未来3天的天气情况
  18. * 1 当天加未来6天的天气情况
  19. * @param {string} params.added_fields 非必填 附加字段,取值:
  20. * alarm 预警信息,仅在type=now时生效。
  21. * index 生活指数信息,仅在type=future时生效
  22. * air 空气质量信息
  23. * @returns {Promise} 返回天气查询结果
  24. * status: number - 状态码,0为正常,其它为异常
  25. * message: string - 对status的描述
  26. * result: object - 天气查询结果
  27. * realtime: object - 实时天气信息,type=now时返回
  28. * forecast: array - 预报天气信息,type=future时返回
  29. */
  30. export function getWeatherInfo(params = {}) {
  31. const { latitude, longitude, type = 'now', added_fields = '' } = params;
  32. // 腾讯地图天气API的key
  33. const TENCENT_MAP_KEY = '2N6BZ-VX5LJ-4GCFA-DGPXT-F4ZNF-7CB5D';
  34. // 构建location参数:纬度,经度
  35. const location = `${latitude},${longitude}`;
  36. // 判断是否为H5环境,H5环境使用代理避免跨域
  37. let baseUrl;
  38. // #ifdef H5
  39. baseUrl = '/tencent-map-api';
  40. // #endif
  41. // #ifndef H5
  42. baseUrl = 'https://apis.map.qq.com';
  43. // #endif
  44. // 构建完整的URL
  45. let url = `${baseUrl}/ws/weather/v1?key=${TENCENT_MAP_KEY}&location=${location}`;
  46. // 添加可选参数
  47. if (type) {
  48. url += `&type=${type}`;
  49. }
  50. if (added_fields) {
  51. url += `&added_fields=${added_fields}`;
  52. }
  53. console.log('天气API请求URL:', url);
  54. return new Promise((resolve, reject) => {
  55. uni.request({
  56. url: url,
  57. method: 'GET',
  58. success: (res) => {
  59. console.log('天气API响应:', res);
  60. if (res.statusCode === 200 && res.data.status === 0) {
  61. resolve(res.data);
  62. } else {
  63. reject(res.data || { message: '天气查询失败' });
  64. }
  65. },
  66. fail: (err) => {
  67. console.error('天气API请求失败:', err);
  68. reject(err);
  69. }
  70. });
  71. });
  72. }
  73. /**
  74. * 获取uni-app定位信息
  75. * @returns {Promise} 返回定位结果
  76. */
  77. export function getLocation() {
  78. return new Promise((resolve, reject) => {
  79. uni.getLocation({
  80. type: 'gcj02', // 返回国测局坐标,适用于腾讯地图
  81. success: (res) => {
  82. resolve({
  83. latitude: res.latitude,
  84. longitude: res.longitude,
  85. accuracy: res.accuracy
  86. });
  87. },
  88. fail: (err) => {
  89. reject(err);
  90. }
  91. });
  92. });
  93. }