vue3定位当前位置,获取当前位置的经纬度

vue3定位当前位置,获取当前位置的经纬度

注意事项(访问地址必须是https)

vue.config.js文件内设置https:true,然后重启一下项目

在这里插入图片描述

获取当前位置经纬度

const etLongitudeLatitude = () => {
  // getStoreList({ latitude: 30.315002570326936, longitude: 120.24681702581334 })
  // return
  //如果该对象存在,那么地理位置服务可用。
  if ('geolocation' in navigator) {
    /* 地理位置服务可用 */
    var options = {
      enableHighAccuracy: true, //布尔值,表示系统是否使用最高精度来表示结果,注意,这会导致较慢的响应时间或者增加电量消耗(比如对于支持gps的移动设备来说)。如果值为false ,设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
      timeout: 5000, //它表明的是设备必须在多长时间(单位毫秒)内返回一个位置。默认直到获取到位置才会返回值。
      maximumAge: 0 //表明可以返回多长时间(即最长年龄,单位毫秒)内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置,而且必须去获取一个真实的当前位置。默认0
    }
    function success(position) {
      latitude = position.coords.latitude //当前位置的纬度
      longitude = position.coords.longitude //当前位置经度
      // alert(`当前位置的纬度:${latitude} 当前位置经度:${longitude}`)
    }
    function error(err) {
      var errorType = ['您拒绝共享位置信息,请去app设置一下!', '获取不到位置信息', '获取位置信息超时']
      alert(errorType[err.code - 1])
      console.log(errorType[err.code - 1])
    }
    navigator.geolocation.getCurrentPosition(success, error, options)
  } else {
    /* 地理位置服务不可用 */
    console.log('无法获取您的位置,请检查定位是否开启或刷新重试')
  }
}```

Vue3和Leaflet结合可以方便地在Web应用中添加地图功能,并定位用户的当前位置。以下是使用Vue3和Leaflet实现定位的基本步骤: 1. **安装依赖**: 首先需要安装`vue-leaflet`库,它是Vue组件化的Leaflet封装。你可以通过npm或yarn来安装: ```bash npm install vue-leaflet @vue/cli-plugin-leaflet # 或者使用yarn yarn add vue-leaflet @vue/cli-plugin-leaflet ``` 2. **配置map组件**: 在`.vue`文件中,引入`<script setup>`语法并初始化Leaflet map,并在模板中添加位置服务的访问权限: ```html <template> <div ref="map" style="height: 400px;"></div> </template> <script setup> import { L, useMap } from &#39;vue-leaflet&#39; const map = useMap({ center: [51.505, -0.09], // 初始经纬度,实际项目中可以用navigator.geolocation获取 zoom: 13, plugins: { LControlPositioning: true // 添加自定义控制面板 } }) const getLocation = async () => { if (navigator.geolocation) { try { const position = await navigator.geolocation.getCurrentPosition() map.flyTo(position.coords) } catch (error) { console.error(&#39;Error getting location&#39;, error) } } else { console.log(&#39;Geolocation is not supported by this browser.&#39;) } } onMounted(() => getLocation()) </script> ``` 3. **处理错误和用户拒绝**: `getCurrentPosition()`函数会返回一个Promise,其中包含用户的地理位置信息。如果用户禁止了定位权限或者设备不支持,你需要处理相应的异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值