浏览器获取当前位置经纬度

<script type="text/javascript">
    //获取当前位置
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            mk = new BMap.Marker(r.point);
            getAddress(r.point);
        }else {
            alert('failed'+this.getStatus());
        }
    });
    //获取地址信息,设置地址label
    function getAddress(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);
        });

    }
</script>

index.html页面

<html>
<head lang="en">
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no"
        name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <title>浏览器中获取当前经纬度</title>
    <link href="../addons/weilive/style/css/user.css" rel="stylesheet">
    <script src="baiduposition.js" type="text/javascript"></script>
    <script src="http://api.map.baidu.com/api?v=2.0&ak=s6vFvPKgaEnI2ImqBpKGDj0m"></script>
    <script src="http://api.map.baidu.com/getscript?v=2.0&ak=s6vFvPKgaEnI2ImqBpKGDj0m&services=&t=20160401164342"
        type="text/javascript"></script>
</head>
<body>
    <div class="app-view">
        <a style="cursor: pointer;" onclick="baiduPosition(35);" class="z-sel"><span>获取经纬度</span></a>
    </div>
    <script type="text/javascript">
        //该js函数是必须要的不然要报错
        function positions(json, cid) {
            //可以获取到了地理位置,跳转页面,然后在跳转的页面在获取经纬度的值
            //window.location.href = "./index.php?i=5&c=entry&do=list&m=weilive&cid=" + cid + "&lng=" + json['lng'] + "&lat=" + json['lat'];
            //alert(json['lng']);
        }
    </script>
</body>
</html>

baiduposition.js代码

document.write("<script src='http://api.map.baidu.com/api?v=2.0&ak=s6vFvPKgaEnI2ImqBpKGDj0m'></script>");
function baiduPosition(cid){
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            var position = {
                lng: r.point.lng,
                lat: r.point.lat
            }
            if(cid == 'sort'){
                sort(position);
            } else {
                positions(position, cid);
            }
            alert('您的位置:'+r.point.lng+','+r.point.lat);
        }
        else {
            //alert('获取当前位置失败,请确定您开启了定位服务');
        }        
    },{enableHighAccuracy: true});
}

posted @ 2022-09-20 11:50  leepandar  阅读(189)  评论(0编辑  收藏  举报