1. 新建一个utilis.js
// 定位
export function ip(callback, error) {
let map, geolocation;
//加载地图,调用浏览器定位服务
const mapObj = new AMap.Map("iCenter");
mapObj.plugin("AMap.Geolocation", function() {
geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000, // 超过10秒后停止定位,默认:无穷大
maximumAge: 60 * 24 * 60 * 60 * 1000, // 定位结果缓存0毫秒,默认:0
convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
showButton: true, // 显示定位按钮,默认:true
buttonPosition: "LB", // 定位按钮停靠位置,默认:'LB',左下角
buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
showCircle: true, // 定位成功后用圆圈表示定位精度范围,默认:true
panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
})
mapObj.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, "complete", onComplete) // 返回定位信息
AMap.event.addListener(geolocation, "error", onError) // 返回定位出错信息
})
// 解析定位结果
function onComplete (data) {
var str = [ "定位成功" ]
// alert(JSON.stringify(data));
let { province, city, district } = data.addressComponent
city = city || province
// setCookie("province", JSON.stringify(data.addressComponent))
// setCookie("city",JSON.stringify(city))
callback && callback(city)
str.push("经度:" + data.position.getLng())
str.push("纬度:" + data.position.getLat())
if (data.accuracy) {
str.push("精度:" + data.accuracy + " 米");
} // 如为IP精确定位结果则没有精度信息
str.push("是否经过偏移:" + (data.isConverted ? "是" : "否"));
// document.getElementById("tip").innerHTML = str.join("<br>");
}
// 解析定位错误信息
function onError(data) {
error && error(data)
console.log('定位失败');
}
}
export default{
ip
}
2. 在index.html引入高德地图
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.8&key=自己的地图key"></script>
3.页面使用
import utilt from '路径地址'
import utils from '../utils/utils'
mounted(){
utils.ip(e=>{
this.city = e
},data=>{
})
}