vue3 获取百度天气

获取百度应用key

需要开通百度天气api,进入 控制台 | 百度地图开放平台

1、创建应用

2、填写名称

3、勾选上天气、百度地图逆地理编码

 4、会得到一个key

vue获取天气

应该用的是接口获取,这里会有跨域的问题,vue上用的是prox,服务器用的nginx我都贴出来

vue

server: {
      port: "8112",
      open: true,
      proxy: {
        // 选项写法
        '/baiduApi': {
          target: 'https://api.map.baidu.com', // 替换为目标API的URL
          changeOrigin: true,               // 更改请求源头信息
          rewrite: path => path.replace(/^\/baiduApi/, ''), // 重写路径
          secure: false,                    // 如果是HTTPS目标,则设置为true
        },
      }
    }

nginx

server {
        listen 443 ssl;
        server_name www.mnxz.fun;

        ssl_certificate /usr/local/nginx/conf/cert/mnxz.fun.pem;
        ssl_certificate_key /usr/local/nginx/conf/cert/mnxz.fun.key;

        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout 5m;

        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;

        root   /usr/local/static/dist;
        index  index.html;

        location / {
            try_files $uri $uri/ /index.html;
        }

        location /baiduApi/ {
            proxy_pass https://api.map.baidu.com/;
            proxy_set_header Host api.map.baidu.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            add_header 'Access-Control-Allow-Origin' 'https://www.mnxz.fun' always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' always;
            add_header 'Access-Control-Allow-Credentials' 'true' always;

            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' 'https://www.mnxz.fun';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
            }
        }
    }

1、先获取用户定位,再用百度逆地理编码接口获取地理编码

//获取百度经纬度和城市地址
export const getBaiduAddress = async (baiduKey) => {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('Geolocation is not supported by this browser.'));
      return;
    }

    navigator.geolocation.getCurrentPosition(
      async (position) => {
        try {
          const { latitude, longitude } = position.coords;
          console.info("lat:" + latitude + " lng:" + longitude);

          // 调用百度地图逆地理编码 API
          const response = await fetch(
            `/baiduApi/reverse_geocoding/v3/?ak=${baiduKey}&output=json&coordtype=wgs84ll&location=${latitude},${longitude}`
          );

          if (!response.ok) {
            throw new Error('Network response was not ok');
          }

          const data = await response.json();
          if (data.status === 0) {
            resolve(data.result.addressComponent);
          } else {
            reject(new Error(`Failed to get location: ${data.message}`));
          }
        } catch (error) {
          reject(error);
        }
      },
      (error) => {
        reject(new Error(`Error getting location: ${error.message}`));
      }
    );
  });
};

2、解析返回数据,得到地理编码

3、再用地理编码获取天气信息,baiduKey 是 第一步的到的key,cityCode是上一步拿到的城市编码

// 获取百度地理天气信息
export const getBaiduWeather = async (baiduKey, cityCode) => {
  const res = await fetch(
    `/baiduApi/weather/v1/?district_id=${cityCode}&data_type=all&ak=${baiduKey}`,
  );
  return await res.json();
};

这样就返回了天气数据

原文地址 码农小站

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值