準備工作:
- 首先,註冊開發者賬號,成爲高德開放平臺開發者
- 登陸之後,在進入「應用管理」 頁面「創建新應用」
- 爲應用添加 Key,「服務平臺」一項請選擇「 Web 端 ( JSAPI ) 」
拿到key之後,在頁面引入高德API和UI組件庫以及相關CSS文件
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src='//webapi.amap.com/maps?v=1.3&key=你申請的key&plugin=AMap.CitySearch'></script>
<script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
引入高德地圖工具包js文件
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
<script src="http://cache.amap.com/lbs/static/es5.min.js"></script>
顯示基礎地圖和提示文字所用到的HTML容器
<div id="allmap" style="position: relative;width: 60%;height: 60%;">
<div id="container"></div>
<div id="tip"></div>
</div>
瀏覽器定位所用到的JS腳本
<script type="text/javascript">
var map, geolocation;
var lng, lat;
//加載地圖,調用瀏覽器定位服務
map = new AMap.Map('container', {
resizeEnable: true,
zoom: 11,
center: [116.397428, 39.90923]//默認的地圖中心經緯度
});
map.plugin('AMap.Geolocation', function () {
geolocation = new AMap.Geolocation({
enableHighAccuracy: true, //是否使用高精度定位,默認:true
timeout: 10000, //超過10秒後停止定位,默認:無窮大
maximumAge: 0, //定位結果緩存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
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete); //返回定位信息
AMap.event.addListener(geolocation, 'error', onError); //返回定位出錯信息
});
//解析定位結果
function onComplete(data) {
var str = ['定位成功'];
//獲取當前地址
//所在省
var province = data.addressComponent.province;
//所在城市
var city = data.addressComponent.city;
if (city.length == 0) {
str.push('所在城市:' + province);
} else {
str.push('所在省:' + province);
str.push('所在城市:' + city);
}
//所在區
var district = data.addressComponent.district;
str.push('所在地區:' + district);
//所在鄉鎮
var township = data.addressComponent.township;
str.push('所在鄉鎮:' + township);
//格式化地址
var formattedAddress = data.formattedAddress;
str.push('詳細地址:' + formattedAddress);
//獲取當前經度緯度
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>');
//調試彈窗
/*lng = data.position.getLng();
lat = data.position.getLat();
alert(data.position.getLng() + "," + data.position.getLat());*/
}
//解析定位錯誤信息
function onError(data) {
document.getElementById('tip').innerHTML = '定位失敗: <br/> <pre>' + JSON.stringify(data, null, 2) + '</pre>';
}
</script>
到這裏爲止,使用高德地圖實現瀏覽器定位已經完成了。