vue 获取公网IP和地理位置

vue 获取公网IP和地理位置

1. 引入脚本

public文件夹下面的index.html中的body标签里加入

<script src="https://pv.sohu.com/cityjson?ie=utf-8"></script>

如:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>111</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  	<script src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
  </body>
</html>

2. 配置.eslintrc.js

.eslintrc.js中添加以下代码以解决returnCitySN未定义问题

globals:{ 
    'returnCitySN': true
  }

3. 直接使用

console.log(returnCitySN)
// {"cip": "21.69.11.119", "cid": "000000", "cname": "北京市"}

const ip = returnCitySN['cip'] || '0.0.0.0'
const city = returnCitySN['cname'] || '未知'

4. 保存后使用

  • App.vuecreated()方法中将ip信息保存到sessionStorage
<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
export default {
  created() {
    sessionStorage.setItem('ip', returnCitySN['cip'] || '0.0.0.0')
    sessionStorage.setItem('city', returnCitySN['cname'] || '未知')
  }
}
</script>
  • 在需要的地方,直接获取
const ip = sessionStorage.getItem('ip')
const city = sessionStorage.getItem('city')
Vue 3 中获取地理位置可以通过浏览器提供的 Geolocation API 来实现。你可以在 Vue 组件中使用以下代码来获取用户的地理位置: ```javascript methods: { getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(this.showPosition, this.showError); } else { console.log("Geolocation is not supported by this browser."); } }, showPosition(position) { console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude); }, showError(error) { switch(error.code) { case error.PERMISSION_DENIED: console.log("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: console.log("Location information is unavailable."); break; case error.TIMEOUT: console.log("The request to get user location timed out."); break; case error.UNKNOWN_ERROR: console.log("An unknown error occurred."); break; } } } ``` 在上述代码中,`getLocation` 方法用于获取用户位置,`showPosition` 方法用于处理成功获取位置信息的回调,`showError` 方法用于处理获取位置信息失败的回调。你可以根据需要对获取到的经纬度进行进一步处理。 然后,在你的 Vue 模板中可以通过按钮或其他事件来触发 `getLocation` 方法: ```html <template> <button @click="getLocation">获取位置</button> </template> ``` 当用户点击按钮时,会触发 `getLocation` 方法并获取用户的地理位置。请注意,由于涉及到浏览器的地理位置功能,用户通常会被要求授权才能使用该功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值