高德地圖進行瀏覽器定位並自定義定位按鈕

要在頁面裏引入高德地圖API進行定位,先要去高德地圖官網申請開發的key,這裏官網文檔寫的很清楚。web

<script src="https://webapi.amap.com/maps?v=1.3&amp;key=你申請的key值&plugin=AMap.Walking"></script>

而後按照API文檔裏接入js代碼,引入後高德地圖會默認給你一個定位按鈕,這個按鈕不能自定義,只能放在地圖的四個角,不過能夠自定義這個按鈕的圖標樣式。api

這裏的小技巧就是在buttonDOM參數設置成一個隱藏的input,這樣在地圖上就看不到默認的定位按鈕了。瀏覽器

    var map, geolocation;
    //加載地圖,調用瀏覽器定位服務
    map = new AMap.Map('dituContent', {
        zoom: 16,
        resizeEnable: true,
    });
    map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默認:true
            timeout: 10000,          //超過10秒後中止定位,默認:無窮大
            buttonOffset: new AMap.Pixel(10, 20),//定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功後調整地圖視野範圍使定位位置及精度範圍視野內可見,默認:false
            buttonDom:'<input hidden="true" >', 
            buttonPosition:'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出錯信息
    });
    //解析定位結果
    function onComplete(data) {
        var str=['定位成功'];
        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>');
    }
    //解析定位錯誤信息
    function onError(data) {
        document.getElementById('tip').innerHTML = '定位失敗';
    }

而後在也面上自定義一個按鈕,並綁定上定位的js方法。spa

<div id="dituContent"></div>
<div id="tip"></div>
<a onClick="geolocation.getCurrentPosition()"></a>  //這裏是自訂的按鈕,幫上定位的方法。
相關文章
相關標籤/搜索