高德地图获取用户地理位置

获取用户地理位置需要获取用户的同意 否则不可以获取用户地理位置
下面直接上代码 复制自己的项目就可以使用 (我用的是高德地图的API)

下面是map.html

<!doctype html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>地理定位</title>
    <!-- 引入css代码-->
    <link rel="stylesheet" type="text/css" href="css/map.css" />
</head>

<body>
    <!--显示地图的容器-->
    <div id="container" tabindex="0"></div>
    <!--引入高德地图的js API代码-->
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.6&key=66d10fd72828b0225bfd3d91c14a5b1b"></script>
    <!--引入js代码-->
    <script type="text/javascript" src="js/map.js"></script>
    <button onclick="getUserPositionInfo()">定位</button>
    您的位置是:<input  type="text" id="position" readonly="readonly" />
</body>

</html>

下面是map.js文件

 var mapObj = new AMap.Map('container',{
            resizeEnable: true,//是否启用调整
            zoom: 10,//变焦
            center: [116.480983, 40.0958]//中心
        });


mapObj.plugin(['AMap.ToolBar','AMap.AdvancedInfoWindow'],function(){
    //创建并添加工具条控件
    var toolBar = new AMap.ToolBar();
    mapObj.addControl(toolBar);

})

function  getUserPositionInfo(){
    var str="需要获取您的位置信息";
   if (confirm(str)) {
      //获取用户位置
   mapObj.plugin('AMap.Geolocation', function () {
    geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位,默认:true
        timeout: 5000,          //超过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
    });
    mapObj.addControl(geolocation);

  geolocation.getCurrentPosition(function(status,result){
    //alert(result.formattedAddress);
    document.getElementById("position").value=result.formattedAddress;
  })

});
   }else{
    //alert("你点击取消了位置获取失败")
   }
}

map.css文件

 body,html,#container{
        height: 500px;
        margin: 0px;
       width: 1000px;
      }

猜你喜欢

转载自blog.csdn.net/testdatas/article/details/80391381
今日推荐