h5接入高德地圖

<!-- 加載地圖JSAPI腳本 -->
<script src="https://webapi.amap.com/maps?v=1.4.11&key=申請的高德地圖的key"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<div id="container"></div>
<div class="info">
    <h4 id='status'></h4><hr>
    <p id='result'></p><hr>
    <p id='result1'>地址信息:</p><hr>
</div>

<script type="text/javascript">
     var lnglatXY='';
    var map = new AMap.Map('container', {
        resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默認:true
            timeout: 40000,          //超過10秒後停止定位,默認:5s
            buttonPosition:'RB',    //定位按鈕的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
            zoomToAccuracy: true,   //定位成功後是否自動調整地圖視野到定位點

        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function(status,result){
            if(status=='complete'){
                onComplete(result)
            }else{
                onError(result)
            }
        });
    });
    //解析定位結果
    function onComplete(data) {
        document.getElementById('status').innerHTML='定位成功'
        var str = [];
        str.push('定位結果:' + data.position);
        lnglatXY=data.position;
        str.push('定位類別:' + data.location_type);
        if(data.accuracy){
            str.push('精度:' + data.accuracy + ' 米');
        }//如爲IP精確定位結果則沒有精度信息
        str.push('是否經過偏移:' + (data.isConverted ? '是' : '否'));
        document.getElementById('result').innerHTML = str.join('<br>');
        //獲取定位之後,調用逆地址解析
        regeocoder();
    }

    //解析地理編碼結果
     function regeocoder() {
         var geocoder = new AMap.Geocoder({  //構造函數,提供地理編碼或逆地理編碼功能
             radius: 1000, //逆地理編碼時,以給定座標爲中心點
             extensions: "all"  //逆地理編碼時,返回信息的詳略,默認值:base,返回基本地址信息;取值爲:all,返回地址信息及附近poi、道路、道路交叉口等信息
         });
         geocoder.getAddress(lnglatXY, function(status, result) {
             if(status === 'complete' && result.info === 'OK') {
                 geocoder_CallBack(result);
             }
         });
         var marker = new AMap.Marker({ //加點
             map: map,
             position: lnglatXY
          });
         map.setFitView();
        }
       function geocoder_CallBack(data) {
           //返回地址描述,
           // regeocode:逆地理編碼結果,僅逆地理編碼返回,
           // formattedAddress:格式化地址,規則:地址信息=基本行政區信息+具體信息;基本行政信息=省+市+區+鄉鎮
         var address = data.regeocode.formattedAddress;
         document.getElementById("result1").innerHTML = address;
     }
    //解析定位錯誤信息
    function onError(data) {
        alert(JSON.stringify(data));
        document.getElementById('status').innerHTML='定位失敗'
        document.getElementById('result').innerHTML = '失敗原因排查信息:'+data.message;
    }

</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章