首先随便一个目录下创建一个js文件,将下列代码复制进入js文件中
//获取经纬度
var jwdData = {
long: undefined,
lat: undefined
}
function getJWdfun(fun) { // 定位获取
let that = this;
uni.showToast({
title: "获取中...",
icon: "none",
duration: 2000,
});
uni.getLocation({
type: "wgs84", //默认为 wgs84 返回 gps 坐标
geocode: "true",
// isHighAccuracy: "true", //是否开启高精度定位,缺点(获取时间比较长)
success: function(res) {
let platform = uni.getSystemInfoSync().platform;
if (platform == "ios") {
//toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。
jwdData.long = res.longitude.toFixed(6);
jwdData.lat = res.latitude.toFixed(6);
} else {
jwdData.long = res.longitude;
jwdData.lat = res.latitude;
}
jwdData.longlat = jwdData.long + "," + jwdData.lat;
fun(jwdData)
},
fail(err) {
if (
err.errMsg ===
"getLocation:fail 频繁调用会增加电量损耗,可考虑使用 wx.onLocationChange 监听地理位置变化"
) {
uni.showToast({
title: "请勿频繁定位",
icon: "none",
});
}
if (err.errMsg === "getLocation:fail auth deny") {
// 未授权
uni.showToast({
title: "无法定位,请重新获取位置信息",
icon: "none",
});
authDenyCb && authDenyCb();
isLocated = false;
}
if (
err.errMsg ===
"getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF"
) {
uni.showModal({
content: "请开启手机定位服务",
showCancel: false,
});
}
},
});
}
export {
getJWdfun
}
然后,在需要获取经纬度的页面引入该方法
注意:路径是自己创建js文件的路径
import {
getJWdfun
} from '@/js/function/jwd.js'
其次就是调用该方法即可
//html代码
<button @click="getJWd" class="dingwei" ></button>
//js代码
// 获取经纬度
getJWd() {
//getJWdfun为刚刚引入的方法名
//通过传递参数的方式传递函数获取js文件获取到的经纬度
getJWdfun(res => {
this.form.longlat = res.longlat
this.form.lat = res.lat
this.form.lng = res.long
})
}