高德地圖瀏覽器定位

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>瀏覽器定位</title>
    <link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.9&key=608d75903d29ad471362f8c58c550daf"></script>
    <script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
<body>
<div id='container'></div>
<div id="tip"></div>
<script type="text/javascript">
/***************************************
因爲Chrome、IOS10等已再也不支持非安全域的瀏覽器定位請求,爲保證定位成功率和精度,請儘快升級您的站點到HTTPS。
***************************************/
    var map, geolocation;
    //加載地圖,調用瀏覽器定位服務
    map = new AMap.Map('container', {
        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
            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 = '定位失敗';
    }
</script>
</body>
</html>
相關文章
相關標籤/搜索