- Geolocation API 用于獲得用戶的地理位置。
- 使用 getCurrentPosition() 方法來獲得用戶的位置
navigator.gentlocation
- getCurrentPosition(successCallback, errorCallback, options) 獲取當(dāng)前的地理位置
- watchPosition(successCallback, errorCallback, options) 監(jiān)聽地理位置變化
- clearWatch() 停止位置監(jiān)聽
position對象
獲取位置成功會調(diào)用 successCallback回調(diào)函數(shù)涂籽, 自動接收position對象
-
coords
- longitude 經(jīng)度
- latitude 緯度
- altitude 海拔
- handing 前進方向
- speed 速度
- altitudeAccuracy 海拔精度
- accuracy 坐標(biāo)精度
timestamp 時間戳
error對象
獲取位置失敗砸抛,調(diào)用errorCallback回調(diào)评雌,調(diào)用 error對象
- code 錯誤代碼
- message 錯誤信息
選項 options
- timeout 超時時間
- enableHighAccuracy 是否最優(yōu)
- maxmunAge 最大緩存時間
注意
- chrome瀏覽器只有在https方式下打開的網(wǎng)頁才能獲取地理位置
- 手上上的大部分瀏覽器,微信 也要求https 才能獲取位置
示例
<body>
<h1>獲取地理定位</h1>
<hr>
<div id="box"></div>
<script>
navigator.geolocation.getCurrentPosition(
function(position){
console.log(position);
var str = "";
str += "當(dāng)前的緯度:"+position.coords.longitude+"<br>";
str += "當(dāng)前的經(jīng)度:"+position.coords.latitude+"<br>";
str += "當(dāng)前的海拔:"+position.coords.altitude+"<br>";
str += "坐標(biāo)經(jīng)度:"+position.coords.accuracy+"<br>";
str += "前進方向:"+position.coords.heading+"<br>";
str += "速度:"+position.coords.speed+"<br>";
document.getElementById("box").innerHTML = str;
},
function(error){
alert("獲取失敗! "+error.code+" , "+error.message);
},
{
timeout:1000, //超時時間
enableHighAccuracy:true, //是否優(yōu)秀
maximumAge:1000000 //最大緩存時間
}
);
</script>
使用百度地圖API 在HTML頁面生成百度地圖
<head>
<meta charset="UTF-8">
<title>地圖</title>
<style>
#mymap{
width:600px;
height:600px;
border:1px solid #ccc;
}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=B8cfd1501ae7f7c55dc3793ee989c354"></script>
</head>
<body>
<h1>地圖演示</h1>
<hr>
<div id="mymap"></div>
<script>
//獲取地理定位
navigator.geolocation.getCurrentPosition(
function(position){
createMap(position.coords.longitude, position.coords.latitude, 15);
},
function(){
alert("獲取地理位置失敗");
createMap(116.404, 39.915, 11)
},
{
timeout:3000
}
);
// * 生成地圖
// * @param number longitude 維度
// * @param number latitude 經(jīng)度
// * @param number zoom
function createMap(longitude, latitude, zoom){
var zoom = zoom || 11; //設(shè)置默認值
// 百度地圖API功能
var map = new BMap.Map("mymap"); // 創(chuàng)建Map實例
map.centerAndZoom(new BMap.Point(longitude, latitude), zoom); // 初始化地圖,設(shè)置中心點坐標(biāo)和地圖級別
map.addControl(new BMap.MapTypeControl()); //添加地圖類型控件
//map.setCurrentCity("北京"); // 設(shè)置地圖顯示的城市 此項是必須設(shè)置的
map.enableScrollWheelZoom(true); //開啟鼠標(biāo)滾輪縮放
}
</script>
</body>
</html>