/*
* 获取用户当前的位置:
* 是异步操作,接受一个成功函数作为回调函数,一个失败函数作为回调函数
* 成功的position对象有两个参数:coords和timestamp
* coords对象的属性:
* longtitude:经度
* latitude:纬度
* accuracy:经纬度坐标的精度,以米为单位
* 失败的error对象的两个参数:code和message
* message:错误文本信息
* code:错误代码,表示错误类型:
* 1:用户拒绝共享位置
* 2:位置无效
* 3:超时
*
*
*
* */
// 简单的获取当前位置
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(geo_success,geo_error)
}
function geo_success(pos){
console.log(pos.coords.latitude, pos.coords.longitude, pos.coords.accuracy)
}
function geo_error(msg){
console.log(msg.code, msg.message)
}
将我的位置准确的展示在地图上
此处用了高德地图的API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>geolocation</title>
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main.css?v=1.0" />
<script src="http://webapi.amap.com/maps?v=1.3&key=您申请的key值"></script>
</head>
<body>
<div id="mapContainer"></div>
<script>
// 高德地图API,显示当前位置
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(geo_success,geo_error)
}
function geo_success(pos){
let map = new AMap.Map('mapContainer',{
// 设置中心点
center : [pos.coords.longitude, pos.coords.latitude],
// 设置缩放级别
zoom : 13
});
let maker = new AMap.Marker({
// 复杂图标
icon : new AMap.Icon({
// 图标大小
size : new AMap.Size(28,37),
// 大图地址
image : "http://webapi.amap.com/images/custom_a_j.png",
imageOffset : new AMap.Pixel(-28,0)
}),
// 在地图上添加点
position : [pos.coords.longitude, pos.coords.latitude]
})
maker.setMap(map)
}
function geo_error(msg){
console.log(msg.code, msg.message)
}
</script>
</body>
</html>










网友评论