百度地圖,拖動地圖,定位marker固定在屏幕中心位置

注:高德地圖相同效果官方demojavascript

如下爲百度地圖相關效果圖:css

注:該例子主要思路是將覆蓋物(marker)經過css定位上去的,可是存在一個問題,當瀏覽器窗口寬度改變時,覆蓋物會自動定位到地圖中心位置,可是地圖可能不會。html

圖片描述

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>map</title>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=你的api key"></script>
    <style type="text/css">
        html{height:100%}
        body{height:100%;margin:0px;padding:0px}
        #container{height:100%}
        .mapicon{
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-100%);
            width: 52px;
            /* margin-top: -200px; */
        }
    </style>
</head>
<body>
<div id="container"></div>
<img src="icon-map.png" class="mapicon" alt="">
<script>
    /**
     * 主要經過地圖的地理位置與像素轉換實現效果
     */
    var map = new BMap.Map("container");
    var point = new BMap.Point(116.404, 39.915);
    /**
     * Y軸偏移量,即地圖可視區域中心點在Y軸的偏移量
     * 當你的地圖底部還有一些輸入框的時候,可視區域集中在
     * 手機的上部,增長偏移量可以將定位地點上移到可視區的
     * 中間,這個量根據頁面狀況自行設定
     * @type {number}
     */
    var offsetY = 200;
    offsetY = 0
    map.centerAndZoom(point, 15);
 
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
        if(this.getStatus() === BMAP_STATUS_SUCCESS){
            var mk = new BMap.Marker(r.point);
            map.addOverlay(mk);
            //將地圖中心移動到可視區中點
            map.panTo(r.point);
            var centerPixel = map.pointToOverlayPixel(map.getCenter());
            //經過設置地圖的中心點,使定位點顯示在手機上部分區域
            map.setCenter(map.overlayPixelToPoint({x:centerPixel.x,y:centerPixel.y+offsetY}));
            map.addEventListener('dragend',function(){
                //得到移動以後地圖中心點的像素位置
                var pixel = map.pointToOverlayPixel(map.getCenter());
                //得到定位圖標所在位置在地圖上的地理位置,實際上定位圖標的像素位置就在地圖中心像素位置相應的偏移量處
                var Point = map.overlayPixelToPoint({x:pixel.x,y:pixel.y-offsetY});
                // var mkn = new BMap.Marker(Point);
                // map.addOverlay(mkn);
            });
        }else {
            alert('failed'+this.getStatus());
        }
    });
</script>
</body>
</html>
相關文章
相關標籤/搜索