随笔 - 133  文章 - 0  评论 - 2  阅读 - 51086

谷歌浏览器模拟手机定位.h5在浏览器上一样可以去获取到当前的城市名称

 

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

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

 

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

 

本地需要开个代理服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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');
});

前端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 检测浏览器是否支持 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   荻!!!!!!!!  阅读(983)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示