百度地图api2.0体验

Posted 性能、可用性、伸缩性、扩展性、安全性、可监控是网站架构最核心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了百度地图api2.0体验相关的知识,希望对你有一定的参考价值。

一、导入百度地图api

<script type="text/javascript" src="/Scripts/jquery.min.js"></script>

 <script src="http://api.map.baidu.com/api?v=2.0&ak=密钥" type="text/javascript"></script>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>易米CMS - Bizmap</title>
<script src="/static/proxy/js/jquery-1.11.1.min.js"></script>
<script src="/static/admin/js/bootstrap.min.js"></script>
<script src="/static/proxy/js/general.js"></script>
<script src="/static/proxy/js/common.js"></script>
<link rel="stylesheet" type="text/css" href="/static/proxy/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/static/proxy/css/font.css">
<link rel="stylesheet" type="text/css" href="/static/proxy/css/style.css">
</head>
<body>
<!-- 头部开始-->
    <div class="navbar navbar-inverse navbar-fixed-top nva">
        <div class="nvamain">
                <div class="navbar navdaohang">
                    <div class="logo"><a href="/index.php?r=proxy/default/index"><img src="/static/img/logo.png" width="215" height="55"></a></div>
                    <ul class="nva_cd">
                        <li><a href="/index.php?r=proxy/default/index" class="cative">首页</a></li>
                        <li><a href="/index.php?r=proxy/biz/index">商家管理</a></li>
                        <li><a href="/index.php?r=proxy/device/index">设备管理</a></li>
<!--                        <li><a href="">人员管理</a></li>-->
                        <li><a href="/index.php?r=proxy/activity/index">商圈活动</a></li>
                        <li><a href="/index.php?r=proxy/ad/index">广告管理</a></li>
                        <li><a href="#">账户管理</a></li>
                        
                        <li><a href="/index.php?r=proxy/bizmap/index">商家分布图</a></li>
                    </ul>
               
                    <div class="admin_user">
                        <ul>
                            <li class="yonghu"><a href="javascript:void(0)" title="proxy">proxy<span class="icon-iconfont-xiala"></span></a></li>
                            <li><a href="/index.php?r=proxy/proxy/settings"><span class="icon-iconfont-touxiang"></span>&nbsp;&nbsp;我的资料</a></li>
                            <li><a href="/index.php?r=proxy/device/index"><span class="icon-iconfont-luyouqi"></span>&nbsp;&nbsp;我的设备</a></li>
                            <li><a href="/index.php?r=proxy/bd/index"><span class="icon-iconfont-jifen"></span>&nbsp;&nbsp;人员管理</a></li>
                            <li><a href="/index.php?r=proxy/recharge/index"><span class="icon-iconfont-chongzhi"></span>&nbsp;&nbsp;充值中心</a></li>
                            <li><a href="/index.php?r=proxy/proxy/repassword"><span class="icon-iconfont-mimazhuanhuan"></span>&nbsp;&nbsp;修改密码</a></li>
                            <li><a href="/index.php?r=proxy/default/logout"><span class="icon-iconfont-tuichudenglu"></span>&nbsp;&nbsp;安全退出</a></li>
                        </ul>
                  </div>
                </div>
        </div>

</div>
<!-- 头部结束-->

    
<style type="text/css">
   #allmap {width: 960px;height: 400px;overflow: hidden;margin:0;border:1px solid #bcbcbc;}
   #allmap img {max-width: none;}</style>


<!-- 中间开始-->
    <div class="container">
         <div  style="margin-top:10px;"></div>
        <div class="row">
            
            <div id="allmap">
                 正在加载地图...
            </div>

         </div> 
        <div class="row">
            <div id="mapInfo" style="margin-top:12px;"></div>
          
        </div>
         <div class="row">
             <div style="margin-top:5px;">
             商家名称
             <input type="text" id="sname" name="sname" value=""  maxlength="15" autocomplete="off" style="margin-top:0px;width:180px;"  class="text small"    />
             <input type="button" id="btnSearch"  class="btn" value="查 询" />
             <input type="button" onclick="ExportMapExcel()"    class="btn" value="导 出" />
               <!--</form>-->
              <div id="loadMapInfo" style="margin-top:12px;"></div>
             </div>

             <div class="biaoge">

                <table id="stable" class="table" >
                <thead>
                    <tr class="biaoti border_d6e1ee">
                        <th>
                            <input type="checkbox" onclick="checkBizAll(this.checked);" />
                        </th>
                        <th>
                            商家名称
                        </th>
                        <th>
                            商家地址
                        </th>
                         <th>
                            查看位置
                        </th>
                    </tr>
                </thead>
                <tbody id="tbodyMList">
         
                </tbody>
                
                 </table>
             </div>
             
         </div>
         
         <form action="/index.php?r=proxy/bizmap/exportmapexcel" style="display:none" id="exportForm" method="post" target="_blank">
             <input type="hidden" id="ids" name="ids" />
         </form>
         
    </div> 
<!-- 中间结束-->


<script src="http://api.map.baidu.com/api?v=2.0&ak=Q0O9mkEqXfiLRRfVLUl7sHDZ" type="text/javascript"></script>
<script src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js" type="text/javascript"></script>
<script src="http://api.map.baidu.com/library/EventWrapper/1.2/src/EventWrapper.min.js" type="text/javascript"></script>



<script type="text/javascript">
    //扩展方法
//    String.prototype.StartWith=function(s){
//     if(s==null||s==""||this.length==0||s.length>this.length)
//      return false;
//     if(this.substr(0,s.length)==s)
//        return true;
//     else
//        return false;
//     return true;
//    }






   //************************
   //基本数据遍历
   //************************
   var bizArray = new Array(); //存放商家数组
   var bizJson = null; //存放商家的json
   var bizCount = 2;//商家总数
   var deviceCount = 2;//设备总数
   
   var pageSize = 10;//每次加载商家个数
   var showCount = 0;//当前列表显示的商家个数
   var loadCount = 2; //当前范围总共有多少个商家
   var map;//百度地图

    //百度地图初始化
    map = new BMap.Map("allmap");
    map.addControl(new BMap.NavigationControl()); //地图平移缩放控件
    map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT})); //比例尺控件
    map.addControl(new BMap.OverviewMapControl({isOpen:true})); //缩略地图控件,默认位于地图右下方,是一个可折叠的缩略地图
    //map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP]}));     //2D图,卫星图   //左上角, 地图类型控件
    map.enableScrollWheelZoom(true);//是否可缩放
    map.addEventListener("tilesloaded",function(){     
      $(".BMap_cpyCtrl").hide();
      $(".anchorBL").hide(); 
    });//地图加载完毕后 隐藏百度图标
    map.centerAndZoom(new BMap.Point(108.95401,34.265193), 5);//设置地图中心和级别 new BMap.Point(116.404, 39.915)

    bizJson = {"2":{"biz_id":"2","biz_name":"\u6613\u7c73wifi","contact_name":"\u6613\u7c73wifi","contact_phone":"123456","address":"\u897f\u5b89\u5e02\u9ad8\u65b0\u4e09\u8def","type_name":"\u7f8e\u98df","sub_type_name":"\u9655\u83dc","lon":"108.95401","lat":" 34.265193","is_online":0,"devices":[{"device_id":"6","device_name":"ddd","reg_number":"111111","auth_mode":"1","is_online":0},{"device_id":"18","device_name":"dfdf","reg_number":"d","auth_mode":"1","is_online":0}]},"5":{"biz_id":"5","biz_name":"\u5546\u5bb62","contact_name":"\u6613\u7c73wifi","contact_phone":"\u7684\u65b9\u6cd5\u65b9\u6cd5\u6cd5","address":"\u897f\u5b89\u5e02\u9ad8\u65b0\u4e09\u8def","type_name":"\u8d2d\u7269","sub_type_name":"\u7efc\u5408\u5546\u573a","lon":"108.954432","lat":" 34.265715","is_online":0,"devices":[]}};

    //**************
    //创建商家信息框
    //**************
    function createInfoTip(biz_id)
    {
        var biz_Name = bizJson[biz_id][biz_name]; //商家名称
        //var is_Online = parseInt(bizJson[biz_id][‘is_online‘]),  //商家是否在线
        var d_count = bizJson[biz_id][devices].length;//商家设备个数
        var address = bizJson[biz_id][address]; //地址
        var contactName = bizJson[biz_id][contact_name];
        var phone = bizJson[biz_id][contact_phone];
        var type_name = bizJson[biz_id][type_name];
        var sub_type_name = bizJson[biz_id][sub_type_name];
  
        var d_html = ""; //设备信息
        for(i = 0; i < d_count; i++) {
             d_html += "设备"+(i+1) +": " + bizJson[biz_id][devices][i][reg_number] + "("+(0 == parseInt(bizJson[biz_id][devices][i][is_online]) ? "<span style=‘color:red;‘>离线</span>":"<span style=‘color:green;‘>在线</span>") + ")"; // + bizJson[biz_id][‘devices‘][i][‘auth_mode‘];
             //if(i!= 0 && i%2 == 0)
             //  {
                  d_html += "<br/>";
             // }
         } 
        
  
        var sContent ="<h3 style=‘margin:0 0 5px 0;padding:0.2em 0;line-height:15px;‘>"+ biz_Name +"</h3>" + 
        //"<div style=‘min-height:120px;‘><img style=‘float:left;margin:4px‘ id=‘imgDemo‘ src=‘"+ imgsrc +"‘ width=‘100‘ height=‘100‘ title=‘"+mName+"‘/>" + 
         "<p style=‘margin:0;line-height:1.5;font-size:13px;‘>行&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业:" +type_name+" - " + sub_type_name+"</p>" + 
        //"<p style=‘height:5px;‘></p>" +
         "<p style=‘margin:0;line-height:1.5;font-size:13px;‘>联 系 人:"+ contactName +"</p>" + 
        //"<p style=‘height:5px;‘></p>" +
        "<p style=‘margin:0;line-height:1.5;font-size:13px;‘>电&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;话:"+phone+"</p>" + 
        //"<p style=‘height:5px;‘></p>" +
        "<p style=‘margin:0;line-height:1.5;font-size:13px;height:30px;‘><span style=‘float:left;width:58px;height:30px;‘>地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址:</span><span >"+address+"</span></p>" + 
        //"<p style=‘height:5px;‘></p>" +
        //"<p style=‘margin:0;line-height:1.5;font-size:13px;‘>简介:"+feature+"</p>" + 
        "<p style=‘height:5px;‘></p>" +

        "<p style=‘margin:0;line-height:1.5;font-size:13px;‘>设备总数:"+ d_count +"</p>" + 
        "<div  style=‘margin:0;line-height:1.5;font-size:13px;‘>"+d_html+"</div>" + 
        "<p style=‘height:3px;‘></p>" +
        "</div>";
        return sContent;
    }

    //*****************
    //创建Marker标注
    //*****************
    function addMarker(biz_id) {
       var biz_Name = bizJson[biz_id][biz_name]; //商家名称
       var is_Online = parseInt(bizJson[biz_id][is_online]);  //商家是否在线
       //var d_count = bizJson[biz_id][‘devices‘].length;//商家设备个数
       var biz_point = new BMap.Point(bizJson[biz_id][lon], bizJson[biz_id][lat]);//商家坐标

        if(0 == is_Online) //离线用灰色图标
        {
           var myIcon = new BMap.Icon("/static/proxy/img/bdmap/marker_gray_default.png", new BMap.Size(10,18) ,{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)});  // {offset: new BMap.Size(50, -50) ,{anchor: new BMap.Size(10,25)}
           var marker = new BMap.Marker(biz_point,{icon:myIcon});
        }
        else
        {//在线用默认图标
          //var myIcon = new BMap.Icon("http://api0.map.bdimg.com/images/marker_red_sprite.png", new BMap.Size(39,25) ,{anchor: new BMap.Size(10,0)} );  //{offset: new BMap.Size(50, -50)
          //var marker = new BMap.Marker(point);
          var myIcon = new BMap.Icon("/static/proxy/img/bdmap/marker_red_default.gif", new BMap.Size(10,18) ,{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)});  // {offset: new BMap.Size(50, -50) ,{anchor: new BMap.Size(10,25)}
          var marker = new BMap.Marker(biz_point,{icon:myIcon});
        }
        // 创建信息窗口对象
        var tip = createInfoTip(biz_id);
        //‘http://api.map.baidu.com/images/iw3.png‘
        var infoWindow = new BMap.InfoWindow(tip,{width:300,background:null}); 
        //添加Marker 

        marker.addEventListener("click", function(){ 
           this.openInfoWindow(infoWindow);
        });
        //marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
        marker.setTitle(biz_Name);
        //setMarker(biz_id,tip,marker);
        map.addOverlay(marker);
        bizJson[biz_id][marker] = marker;
        bizArray.push(biz_id);
        //bizJson[biz_id][‘infoWindowHtml‘] = tip; 
    }

    //加载地图数据
    function initMapData()
    {
        //设置商家数据
        $("#mapInfo").text("商家总数:" + bizCount +" 设备总数:" +deviceCount);
        $("#loadMapInfo").html("当前范围商家:"+ loadCount);

         //循环添加Marker
         for(var b in bizJson){  
              addMarker(b);
          }  
         //加载列表
         loadBizList(true);
    }

    //查看商家
    function findBiz(b)
    {
        var ckmarker = bizJson[b][marker];//bizJson[2][‘infoWindowHtml‘
        ckmarker.dispatchEvent("click"); 
        //BMapLib.EventWrapper.trigger(ckmarker, ‘click‘, {‘type‘: ‘onclick‘, target: ckmarker});
    }

    //全选功能
    function checkBizAll(isCheck)
    {
       $("#tbodyMList :visible").find(":checkbox").prop("checked",isCheck);
    }
    
    //导出功能
    function ExportMapExcel()
    {
       var bids = getCheck({obj:"#tbodyMList"});
       if(bids != "")
       {
          $("#ids").val(bids);
          $("#exportForm").submit();
          //window.open(‘exportmapexcel?ids=‘+bids);
       }
       else
       {
           showAlert({msg:请选择需要导出的商家});
          
          //alert("请选择需要导出的商家");
       }
      
    }
    
    
    //***********************
    //加载可视范围内的商家列表 flag是否是初次加载
    //***********************
    function loadBizList(flag,sname)
    {
        //按距离排序
        //按距离从小到大排序
        bizArray.sort(function(a,b){
           return BMapLib.GeoUtils.getDistance(map.getCenter(),new BMap.Point(bizJson[a][lon],bizJson[a][lat])) - BMapLib.GeoUtils.getDistance(map.getCenter(),new BMap.Point(bizJson[b][lon],bizJson[b][lat]));
        });
        
        showCount = 0;
        loadCount = 0;
        var alltr = "";
        var slon = 0;
        var slat = 0;
        if(null != sname && "" != sname)
         {
             for (i = 0; i < bizCount; i++) {   
                 if(bizJson[bizArray[i]][biz_name] == sname)
                 {
                      slon = bizJson[bizArray[i]][lon];
                      slat = bizJson[bizArray[i]][lat];
                      break;
                 }   
             }
             
//             for(var b in bizJson){  
//                 if(bizJson[b][‘biz_name‘].StartWith(sname))
//                 {
//                      slon = bizJson[b][‘lon‘];
//                      slat = bizJson[b][‘lat‘];
//                      break;
//                 }
//              }  
         }
         else
         {
             if(flag)
             {
//                for(var b in bizJson){  
//                    alltr += createTr(b,loadCount);
//                    loadCount +=1;
//                 }  
                for (i = 0; i < bizCount; i++) {  
                    alltr += createTr(bizArray[i],loadCount);
                    loadCount +=1;
                }
                 
             }
             else
             {
                 
                for (i = 0; i < bizCount; i++) {
                    var result = BMapLib.GeoUtils.isPointInRect(new BMap.Point(bizJson[bizArray[i]][lon], bizJson[bizArray[i]][lat]), map.getBounds());
                    if(result)
                    {
                        alltr += createTr(bizArray[i],loadCount);
                        loadCount +=1;
                    }   
                 } 
                
//                for(var b in bizJson){  
//                    var result = BMapLib.GeoUtils.isPointInRect(new BMap.Point(bizJson[b][‘lon‘], bizJson[b][‘lat‘]), map.getBounds());
//                    if(result)
//                    {
//                        alltr += createTr(b,loadCount);
//                        loadCount +=1;
//                    }
//                 }  
                 
             }
         }
         if(loadCount != 0)
          {
              alltr += <tr class="trbor"><td colspan="4" style="text-align:center;">+ (showCount == loadCount ? 全部加载完毕 : <a href="javascript:void(0);" id="btnMore" onclick="clickLoadMore(this)">点击加载更多</a> )+</td></tr>;
          }
          $("#tbodyMList").html("").append(alltr);
          $("#loadMapInfo").html("当前范围商家:"+ loadCount);
          if(slon != 0 && slat != 0)
          {
             //地图中心
             map.centerAndZoom(new BMap.Point(slon, slat),12);//级别
          }
    }
    
    
    //创建tr
    function createTr(b ,trIndex)
    {
        var  trStyle = ‘‘;
        if((trIndex + 1) > pageSize)
        {
           trStyle = style="display:none;";
           //mobj.marker.setAnimation(null);
           if(1 == parseInt(bizJson[b][is_online]))
           {
              bizJson[b][marker].setIcon(new BMap.Icon("/static/proxy/img/bdmap/marker_red_default.gif",new BMap.Size(10,14),{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)}));
           }
           else
           {
              bizJson[b][marker].setIcon(new BMap.Icon("/static/proxy/img/bdmap/marker_gray_default.png",new BMap.Size(10,14),{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)}));
           }
        }
        else{
           showCount +=1;
           if(1 == parseInt(bizJson[b][is_online]))
           {
             bizJson[b][marker].setIcon(new BMap.Icon("http://api0.map.bdimg.com/images/marker_red_sprite.png",new BMap.Size(20,32),{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)}));
           }
           else
           {
             bizJson[b][marker].setIcon(new BMap.Icon("/static/proxy/img/bdmap/marker_gray_sprite.png",new BMap.Size(20,32),{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)}));
           }
           //mobj.marker.setAnimation(BMAP_ANIMATION_BOUNCE); 
        }
        if(b != null && b != 0)
        {
             var trHtml = <tr class="trbor" + trStyle + id="mtr+trIndex+"><td ><input type="checkbox" value="+b+" smid = " + b + " /></td>;
             trHtml+= <td >+ bizJson[b][biz_name] +</td>;
             trHtml+= <td >+ bizJson[b][address] +</td>;
             trHtml+= <td style="cursor:pointer;" onclick="findBiz(+ b +)" name="mclick">;
             trHtml+= <div name="mid" style="display:none">+ b +</div>;
             trHtml+= 查看位置</td>;
             trHtml+= </tr>;
             return trHtml;
        }
        return "";
    }


   //点击显示更多
    function clickLoadMore(obj)
    {
        if(loadCount > showCount)
        {
           var lcount = (showCount + pageSize) > loadCount ? loadCount : (showCount + pageSize);
           for (var i = showCount; i < lcount; i++) {
                $("#mtr"+i).show();
                var id = $("#mtr"+i).find("div[name=‘mid‘]").text();
                showCount += 1;
               if(1 == parseInt(bizJson[id][is_online]))
               {
                   bizJson[id][marker].setIcon(new BMap.Icon("http://api0.map.bdimg.com/images/marker_red_sprite.png",new BMap.Size(20,32),{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)}));
               }
               else
               {
                  bizJson[id][marker].setIcon(new BMap.Icon("/Content/img/bdmap/marker_gray_sprite.png",new BMap.Size(20,32),{anchor: new BMap.Size(9,25),infoWindowAnchor: new BMap.Size(10, 0)}));
               }
           }
           if(loadCount == showCount)
           {
              $(obj).html("全部加载完毕");
           }
        }
    }


    
    //瀑布流
    var totalheight = 0;
    function loadData() {
        totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
        if ($(document).height() <= totalheight) {
            //加载数据
            clickLoadMore($("#btnMore"));
        }
    }
    
    //ready
    $(function(){
          if(bizJson != null) //如果查询到得商家不为空
          {
              initMapData();

              $("#btnSearch").click(function () {
                 loadBizList(true,$("#sname").val());
              });

              $(window).scroll(function () {
                  //console.log("滚动条到顶部的垂直高度: " + $(document).scrollTop());
                  //console.log("页面的文档高度 :" + $(document).height());
                  //console.log(‘浏览器的高度:‘ + $(window).height());
                 loadData();
              });
              
              
             map.addEventListener("moveend",function(){ loadBizList(false);});//地图移动结束事件
             map.addEventListener("zoomend",function(){ loadBizList(false);});//缩放结束事件
             map.addEventListener("dragend",function(){ loadBizList(false);});//拖拽结束事件
             map.addEventListener("resize",function(){ loadBizList(false);});//可视区域发生变化事件
          }
    });
   
</script>
<!-- 版权开始-->
    <div class="modal-footer">© Copyright 2014 Powered by e</div>
<!-- 版权结束-->
</body>
</html>

 

以上是关于百度地图api2.0体验的主要内容,如果未能解决你的问题,请参考以下文章

java使用百度地图,进行点定位,点位置不正确

百度离线地图发布源代码

android studio下百度地图sdk的初体验

百度地图API开发一——仿照现有测距实现测量面积功能

Vue+Antd搭配百度地图实现搜索定位等功能

如何离线发布百度地图