百度地图API获取当前位置

异步加载获取当前位置

//百度地图API功能
    function loadJScript() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://api.map.baidu.com/api?v=2.0&ak=zUGhOxEtT50sUhK1WCoMeHXleEG4q1un&callback=init";
        document.body.appendChild(script);
    }


    function init() {
        var longitude =118.7029550000;//经度
        var latitude =32.1632910000;//纬度
        var map = new BMap.Map("allmap");            // 创建Map实例
        var point = new BMap.Point(114.3115860000,30.5984670000); // 创建点坐标
        map.centerAndZoom(point,15);


        if( longitude!= "" && latitude!= ""){
            map.clearOverlays();
            var new_point = new BMap.Point(longitude,latitude);
            map.centerAndZoom(new_point, 15);
            //var marker = new BMap.Marker(new_point);  // 创建标注

            var myIcon = new BMap.Icon("../images/dw_icon.png", new BMap.Size(26,77));
            var marker2 = new BMap.Marker(new_point,{icon:myIcon});
            map.addOverlay(marker2);              // 将标注添加到地图中

            map.panTo(new_point);

            //获取当前位置
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function(){
                if(this.getStatus() == BMAP_STATUS_SUCCESS){
                    getAddress(new_point);
                    console.log(BMAP_STATUS_SUCCESS)
                }else {
                    alert('failed'+this.getStatus());
                }
            });
            //获取地址信息,设置地址label
            function getAddress(point){
                console.log(point);
                var gc = new BMap.Geocoder();
                gc.getLocation(point, function(rs){
                    var addComp = rs.addressComponents;
                    var address =  addComp.province +  addComp.city + addComp.district + addComp.street + addComp.streetNumber;//获取地址
                    console.log(address);
                });
            }

        }




    }

    window.onload = loadJScript;  //异步加载地图

获取当前位置



你可能感兴趣的:(JS)