一、使用高德地图获取当前的经纬度转化为详细位置
1、在index.html入口文件加上
<script type="text/javascript">
// 一定要安全密钥先写在前,key在后,不然无效
window._AMapSecurityConfig = {
securityJsCode: "89d71515768db4889a1befe965c58c75",
}
</script>
2、直接复制
let aMapScript = document.createElement('script');
aMapScript.setAttribute('src', 'https://webapi.amap.com/maps?v=1.4.11&key=自己的高德key&plugin=AMap.CitySearch');
aMapScript.onload = () => {
AMap.plugin(['AMap.Geolocation', 'AMap.Geocoder'], () => {
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true,
timeout: 5000,
zoomToAccuracy: true,
showButton: true,
buttonPosition: 'LB',
panToLocation: true,
GeoLocationFirst: true
// enableHighAccuracy: true,
// timeout: 10000,
// buttonOffset: new AMap.Pixel(10, 20),
// zoomToAccuracy: true,
// buttonPosition: 'RB'
});
const geocoder = new AMap.Geocoder();
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', (data) => {
const lnglat = [data.position.lng, data.position.lat];
geocoder.getAddress(lnglat, (status, result) => {
if (status === 'complete' && result.info === 'OK') {
const addressComponents = result.regeocode.addressComponent;
const province = addressComponents.province;
const city = addressComponents.city;
const district = addressComponents.district;
this.city = province
this.cityMarket = city || district
console.log('省:', province);
console.log('市:', city);
console.log('区:', district);
} else {
console.log('逆地理编码失败:', result);
}
});
});
AMap.event.addListener(geolocation, 'error', (data) => {
console.log(data);
console.log('定位失败');
});
});
};
document.head.appendChild(aMapScript);
备注:谷歌、360等部分浏览器不支持该功能 会说获取位置失败\超时
二、使用腾讯地图获取ip转化为详细信息
1、安装vue-jsonp
npm i vue-jsonp -S
2、在main.js中导入vue-jsonp
import {VueJsonp} from 'vue-jsonp'; //注意:这里要加花括号
Vue.use(VueJsonp);
3、直接复制
//使用腾讯服务获取ip和归属地
getIpAddress(){
this.$jsonp('https://apis.map.qq.com/ws/location/v1/ip', {
key:xxxxxx,//注意:这里使用key为键名
output:'jsonp',
}).then(response => {
console.log(response);
console.log(response.result.ip);
console.log(response.result.ad_info.nation);
console.log(response.result.ad_info.province);
console.log(response.result.ad_info.city);
}).catch(error => {
console.error(error);
});
},
备注:使用腾讯api每天有次数限制