第一种 uniapp
uniapp 封装的方法可以拿到城,市,县,经纬度。
实例:
//获取位置GetLOcation: function() {var that = this;uni.getLocation({type: 'gcj02',success: (res) => {console.log(res)var latitude = parseFloat(res.latitude);var longitude = parseFloat(res.longitude);}});},
官网地址:https://uniapp.dcloud.io/api/location/location?id=%e6%b3%a8%e6%84%8f
第二种: javascript iframe方法
下面的操作如果你是vue的就直接引入到index.html文件中。
如果是uni-app就比较麻烦了:
1.首先新建一个template.h5.html文件;
2.在manifest.json -> 源码视图 -> h5 -> 添加 “template” : “template.h5.html”
在创建文件中引入:
<iframe id="geoPage" width=0 height=0 frameborder=0 style="display:none;" scrolling="no"src="https://apis.map.qq.com/tools/geolocation?key=腾讯地图key&referer=myapp"></iframe>
在 body 中添加
<div v-html="str"></div>
在要使用的文件中添加下面代码:
var options = {enableHighAccuracy: true,maximumAge: 30000,timeout: 12000}window.locationCallback = function(err, position) {if (err) {showError(err);return;}showPosition(position);}this.str = '<iframe src="javascript:(function(){ ' +'window.navigator.geolocation.getCurrentPosition(' +'function(position){parent && parent.locationCallback && parent.locationCallback(null,position);}, ' +'function(err){parent && parent.locationCallback && parent.locationCallback(err);}, ' +'{enableHighAccuracy : ' + options.enableHighAccuracy + ', maximumAge : ' + options.maximumAge + ', timeout :' +options.timeout + '})' +';})()" style="display:none;"></iframe>';window.showPosition = function(position) {var lat = position.coords.latitude; //纬度var lag = position.coords.longitude; //经度// var lags = position.address.province;//城市名称// alert(lags)// alert('纬度:' + lat + ',经度:' + lon)}window.showError = function(error) {switch (error.code) {case error.PERMISSION_DENIED:alert('用户不允许地理定位!');break;case error.POSITION_UNAVAILABLE:alert('无法获取当前位置!');break;case error.TIMEOUT:alert('操作超时!');break;case error.UNKNOWN_ERROR:alert('未知错误!');break;}}
第三种: 腾讯地图
支持 浏览器,手机端,app 端目前不太支持。
先去腾讯地图官方申请 key 值 然后到项目中的 manifest.json 文件中的 h5 配置中添加你的腾讯地图 key值
腾讯地图 API 官方地址:https://lbs.qq.com/
在 项目中的 template.h5.html 文件中引入
<script charset="utf-8" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=腾讯开发者key值"></script>
应用实例:
let that = thisvar geolocation = new qq.maps.Geolocation("腾讯开发者 key 值", "myapp");var options = {timeout: 8000 //延时};// 定位成功之后调用的方法function showPosition(position) {console.log(position)let lat = position.lat;let lng = position.lng;}function showErr() {// alert('定位失败,请稍后重试');geolocation.getLocation(showPosition, showErr, options);//回调,如果获取定位失败,就重新来一次}geolocation.getLocation(showPosition, showErr, options);