1.HTML
<div id="container"></div>
2.高德地圖webapi引入
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.13&key=在高德地圖開放平臺(tái)獲取到的key"></script>
3.js詳細(xì)代碼奉上嘁傀,若有問題可留言 親測可用
function getmap(){
var map = new AMap.Map('container', {
resizeEnable: true
});
AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位膝昆,默認(rèn):true
timeout: 10000, //超過10秒后停止定位仅叫,默認(rèn):5s
buttonPosition:'RB', //定位按鈕的团航欤靠位置
buttonOffset: new AMap.Pixel(10, 20),//定位按鈕與設(shè)置的停靠位置的偏移量,默認(rèn):Pixel(10, 20)
zoomToAccuracy: true, //定位成功后是否自動(dòng)調(diào)整地圖視野到定位點(diǎn)
});
map.addControl(geolocation);
geolocation.getCurrentPosition(function(status,result){
if(status=='complete'){
onComplete(result)
}else{
onError(result)
}
});
});
// 解析定位結(jié)果
function onComplete(data) {
localStorage.setItem('ptLat',data.position.lat);
localStorage.setItem('ptLng',data.position.lng);
geocoder(data.position.lng, data.position.lat);//已獲取到的經(jīng)緯度傳入?yún)?shù)即可
}
//解析定位錯(cuò)誤信息
function onError(data) {
document.getElementById('status').innerHTML='定位失敗'
document.getElementById('result').innerHTML = '失敗原因排查信息:'+data.message;
}
//經(jīng)緯度轉(zhuǎn)換為地址
function geocoder(lnglatX, lnglatY, cityCode) {
var geocoder = new AMap.Geocoder({
city : cityCode, //城市讽坏,默認(rèn):“全國”
radius : 1000 //范圍,默認(rèn):500
});
geocoder.getAddress([lnglatX, lnglatY], function(status, result) {
if (status === 'complete' && result.info === 'OK') {
geocoder_CallBack(result);
}
});
}
function geocoder_CallBack(data) {
var geocode = data.regeocode;
$('span.address_z').html(geocode.formattedAddress);//獲取到的詳細(xì)地址
}
}