如果有位置需要定位.电脑上没有默认的经纬度.可以在这里调.

点击开发者控制面板右侧的「三点」按钮——然后单击「Sensors」(传感器)选项——在「Geolocation」(地理位置)右侧下拉列表中选择——「Custom location」(自定义位置),在「latiude」纬度、「longitude」中填写坐标信息即可。

 

比如58同城的app在第一次获取位置信息时,会请求授权并将授权后获取到的位置信息存储在本地,以后每次打开app时会自动读取本地存储的位置信息,而不需要再次请求授权。但是,如果用户切换了城市或者移动到了一个新的位置,58同城的app会重新请求获取位置信息,以便更新用户当前位置。因此,当您切换城市或移动到新的位置时,58同城的app会弹出提示框询问是否允许获取新的位置信息。如果您允许获取,那么新的位置信息会被存储在本地,并在以后的使用中被自动读取。

 

本地需要开个代理服务器

const express = require('express');
const request = require('request');
const cors = require('cors');
const app = express();

app.use(cors()); // 设置允许跨域请求

app.get('/api/reverse-geocoding', (req, res) => {
  const { location } = req.query;
  const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=Y7CIi5QBZD19YYULUYpPYtNdKBy5eavF&output=json&coordtype=wgs84ll&location=${location}`;
  request(url, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      res.send(body);
    } else {
      res.status(response.statusCode).send(error);
    }
  });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

前端代码

 // 检测浏览器是否支持 geolocation API
    if (navigator.geolocation) {
      // 获取当前位置信息
      navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
    } else {
      console.log('浏览器不支持 geolocation API');
    }

    // 获取位置信息成功时的回调函数
    function successCallback (position) {
      const { latitude, longitude } = position.coords;
      // 调用自己的服务器获取城市名称
      const url = `http://localhost:3000/api/reverse-geocoding?location=${latitude},${longitude}`;
      fetch(url)
        .then(response => response.json())
        .then(data => {
          const city = data.result.addressComponent.city;
          // 获取到城市名称后可以进行相关操作,比如展示当前城市的天气信息等
          console.log('当前城市:', city);
        })
        .catch(error => {
          console.log('获取城市名称失败:', error);
        });
    }

    // 获取位置信息失败时的回调函数
    function errorCallback (error) {
      switch (error.code) {
        case error.PERMISSION_DENIED:
          console.log('用户拒绝授权获取位置信息');
          break;
        case error.POSITION_UNAVAILABLE:
          console.log('位置信息不可用');
          break;
        case error.TIMEOUT:
          console.log('获取位置信息超时');
          break;
        default:
          console.log('获取位置信息失败');
          break;
      }
    }

本地开代理服务是解决百度接口去解析经纬度的时候跨域的问题.公司开发的话找后端解决.

 

posted on 2023-01-10 14:19  huyadi  阅读(791)  评论(0编辑  收藏  举报