首页 > 代码库 > 百度地图在项目中的使用(JS)

百度地图在项目中的使用(JS)

废话先:


这个项目是使用ASP.NET MVC 写的,而关于百度地图在项目中的应用不限于ASP.NET MVC 因为我大部分的API的使用是通过Javascript,想在项目中使用百度地图,你得先成为百度的开发者,具体的步骤,在本篇博文中不多叙述。

主题:


在使用百度地图的时候,你得先要获得一个ak

12

这里就是点击创建应用,它提供了几个类别1.for server  2.for mobile 3.for browser,在这里呢,因为我们是通过一个for browser来了解百度地图,所以在创建应用时,勾选for browser,这里有一点需要注意就是在下面的Referer中填上一个*,因为我们在这里就是一个测试,还没有真正的应用到项目中,点击创建后,读者所见到的应该和我的差不多,有了ak,下面的就好办了。

首先呢,在你的ASP.NET MVC 项目里创建一个Controller,并且创建一个与index action对应的view,那我们在这个index.cshtml中要引入这样一段:<script type="text/javascript" src=http://api.map.baidu.com/api?v=2.0&ak=your_ak></script>

当然了还需要这样一个<div>这个层的作用就是显示你的地图,我的是这么写的:

<div id="container" style="width:85%;height:100%;float:left;border-right:2px solid #bcbcbc"></div>

window.onload = function () {
        mapPoint = new BMap.Point(114.433694, 30.4503);
        map = new BMap.Map("container");
        map.centerAndZoom(mapPoint, zoom);//初始化地图,设置中心点坐标和地图的级别
        map.enableScrollWheelZoom();
        map.addControl(new BMap.NavigationControl());//添加默认缩放平移控件
 
        //从服务获得客户端的具体数据
        $.getJSON("/BMap/getMapInfo", function (data) {
            _initCom(data);
            RefreshMarker();
        });
    }
<style></style><style></style><style></style>

这是我一段js代码,就是在这个view加载的时候立马执行地图的定位和初始化,相应的注解我都在上面注释了,

下面这是_initCom方法的具体代码:

    function _initCom(data) {
        CommunityList.length = 0;
        if ($.trim(data) !== "") {
            var strCommunityList = data.split(";"); //分割字符串
            $.each(strCommunityList, function (i,item) {    //遍历
                if ($.trim(item) !== "") {
                    var instance = item.split(","),
                        community = {};     //保存数据信息
                    community.lng = instance[0];
                    community.lat = instance[1];
                    community.content = instance[2];
                    community.createTime = instance[3];
                    community.studentId = instance[4];
                    if (community.lng !== -1000 && community.lat !== -1000) {
                        CommunityList[CommunityList.length] = community;
                    }
                }
            });
        }
    }
<style></style>

这是在我得到了相应的数据之后将数据格式化为我想要处理的字符格式。

下面这是整个的js代码,我先为大家贴出来,好让大家有一个整体的感受:

   1:   
   2:  <script type="text/javascript" src="http://www.mamicode.com/http://api.map.baidu.com/api?v=2.0&ak=your_ak"></script>
   3:  <div id="container" style="width:85%;height:100%;float:left;border-right:2px solid #bcbcbc"></div>
   4:   
   5:  <div id="searchResult" style="height:100%;width:15%;float:right;background-color:#c7c7c7">
   6:      <div id="userControl" style="margin-top:100px;">
   7:          <p>请输入学生的ID</p>
   8:          <input id="keyword" type="text" style="width:150px" />
   9:          <input type="button" value=http://www.mamicode.com/"搜索" onclick="search()" />
  10:          <input type="button" value=http://www.mamicode.com/"刷新地图" onclick="RefreshMarker()" style="margin-top:50px;float:right" />
  11:      </div>
  12:      
  13:  </div>
  14:   
  15:  <script type="text/javascript">
  16:      var map = null,
  17:          zoom = 15,
  18:          selfmarker = null,
  19:          mapPoint = null,
  20:          CommunityList = [], //数据集合
  21:          MarkerList = [];    //标注集合
  22:   
  23:      function search() {
  24:          var KW = $(‘#keyword‘).val().trim(),
  25:              reg = /^[0-9]*$/;       //这边可以根据需要进一步的正则!
  26:          if (!reg.test(KW)) {
  27:              alert(‘请键入学生的ID‘);
  28:          } else {
  29:              _search = [];
  30:              if (MarkerList.length > 0) {
  31:                  for (var i = 0; i < CommunityList.length; i++) {
  32:                      if (CommunityList[i].studentId === KW) {
  33:                          _search.push(CommunityList[i]); //将符合要求的学生添加到一个数组中
  34:                      }
  35:                  }
  36:                  if (_search.length === 0) {
  37:                      alert("没能找到您搜索的学生,请确保Id正确");
  38:                      return false;
  39:                  } else {
  40:                      searchResult(_search);
  41:                  }
  42:                 
  43:              } else {
  44:                  map.centerAndZoom(mapPoint, zoom);
  45:              }
  46:          }
  47:      }
  48:   
  49:      function searchResult(_data) {
  50:          map.clearOverlays();        //当显示搜索结果时,先清除页面上的marker
  51:          $.each(_data, function (i, data) {
  52:              var lng = data.lng,
  53:             lat = data.lat,
  54:             content = data.content,
  55:             time = data.createTime,
  56:             point = new BMap.Point(lng, lat),
  57:             marker = new BMap.Marker(point),
  58:             label = new BMap.Label(data.studentId);
  59:              marker.setLabel(label);
  60:              map.addOverlay(marker);
  61:              label.setStyle({
  62:                  borderColor: "#808080",
  63:                  color: "#333",
  64:                  cursor: "pointer"
  65:              });
  66:   
  67:              (function () {
  68:                  var options = {
  69:                      width: 280,
  70:                      height: 128,
  71:                      title: "<strong>学生信息</strong>"
  72:                  }
  73:                  var _data = http://www.mamicode.com/data,
  74:                      _Iw = createInfoWindow(_data, options),
  75:                      _marker = marker;
  76:                  _marker.addEventListener("click", function () {
  77:                      this.openInfoWindow(_Iw);
  78:                  });
  79:                  _marker.addEventListener("open", function () {
  80:                      _marker.getLabel().hide();
  81:                  });
  82:                  _marker.addEventListener("close", function () {
  83:                      _marker.getLabel().show();
  84:                  });
  85:                  label.addEventListener("click", function () {
  86:                      _marker.openInfoWindow(_Iw);
  87:                  })
  88:              })();
  89:          });
  90:          
  91:      }
  92:   
  93:      function _initCom(data) {
  94:          CommunityList.length = 0;
  95:          if ($.trim(data) !== "") {
  96:              var strCommunityList = data.split(";"); //分割字符串
  97:              $.each(strCommunityList, function (i,item) {    //遍历
  98:                  if ($.trim(item) !== "") {
  99:                      var instance = item.split(","),
 100:                          community = {};     //保存数据信息
 101:                      community.lng = instance[0];
 102:                      community.lat = instance[1];
 103:                      community.content = instance[2];
 104:                      community.createTime = instance[3];
 105:                      community.studentId = instance[4];
 106:                      if (community.lng !== -1000 && community.lat !== -1000) {
 107:                          CommunityList[CommunityList.length] = community;
 108:                      }
 109:                  }
 110:              });
 111:          }
 112:      }
 113:   
 114:   
 115:      function addMarker(commuinity) {
 116:          selfmarker = _createNorMarker(commuinity);
 117:          map.addOverlay(selfmarker);
 118:          MarkerList[MarkerList.length] = selfmarker;
 119:      }
 120:   
 121:   
 122:      function RefreshMarker() {
 123:          clearMarker();
 124:          map.clearOverlays();
 125:          if (CommunityList.length > 0) {
 126:              for (var i = 0; i < CommunityList.length; i++) {
 127:                  var community = CommunityList[i];
 128:                  addMarker(community);
 129:              }
 130:   
 131:              var fistcommuinty = CommunityList[0],
 132:                  firstPoint = new BMap.Point(fistcommuinty.lng, fistcommuinty.lat);
 133:              map.centerAndZoom(firstPoint, zoom);
 134:          } else {
 135:              map.centerAndZoom(mapPoint, zoom);
 136:          }
 137:      }
 138:   
 139:      function clearMarker() {
 140:          if (MarkerList.length > 0) {
 141:              for (var i = 0; i < CommunityList.length; i++) {
 142:                  var community = CommunityList[i];
 143:                  addMarker(community);
 144:              }
 145:          } else {
 146:              map.centerAndZoom(mapPoint, zoom);
 147:          }
 148:      }
 149:   
 150:      //创建信息提示窗
 151:      function createInfoWindow(commuinity,options) {
 152:          var content = "<br />" + "这是学生Id为:" + commuinity.studentId + "的内容<br/>" + commuinity.content + "<br />提交时间:" + commuinity.createTime;
 153:          var infoWindow = new BMap.InfoWindow(content, options);
 154:          return infoWindow;
 155:      }
 156:   
 157:      function _createNorMarker(commuinity) {
 158:          var point = new BMap.Point(commuinity.lng, commuinity.lat),
 159:              marker = new BMap.Marker(point, { offset: new BMap.Size(0, 13) });
 160:          marker.addEventListener("click", function (e) {
 161:              var options = {
 162:                  width: 280,
 163:                  height: 128,
 164:                  title: "<strong>学生具体地理信息</strong>"
 165:              }
 166:               
 167:              infoWindow = createInfoWindow(commuinity,options);
 168:              map.openInfoWindow(infoWindow, e.point);
 169:          });
 170:   
 171:          marker.tag = commuinity;
 172:          map.addOverlay(marker);
 173:          return marker;
 174:      }
 175:   
 176:      //窗口打开就加载
 177:      window.onload = function () {
 178:          mapPoint = new BMap.Point(114.433694, 30.4503);
 179:          map = new BMap.Map("container");
 180:          map.centerAndZoom(mapPoint, zoom);//初始化地图,设置中心点坐标和地图的级别
 181:          map.enableScrollWheelZoom();
 182:          map.addControl(new BMap.NavigationControl());//添加默认缩放平移控件
 183:   
 184:          //从服务获得客户端的具体数据
 185:          $.getJSON("/BMap/getMapInfo", function (data) {
 186:              _initCom(data);
 187:              RefreshMarker();
 188:          });
 189:      }
 190:  </script>
<style></style>

在这里大家可能会注意到我写了一个Search的方法,那么为什么需要写这个方法呢,这也是因为在这个项目中的需要,就是我从数据库当中获得了学生的具体上传的地理数据,但是,我现在就想知道一个学生近一段时间上传的具体的数据,我总不会一个个的找吧,几个学生还好,要是成百上千,那不得要人命了啊!在这里呢,我搜索的数据是,静态数据的的搜索,也就是数据已经加载完成了,我从现有的数据中搜索,在这里我的那些坐标也就是我通过百度坐标获取这个工具获得的。

下面的这段代码是我在BMapController中的:

   1:  public ActionResult getMapInfo()
   2:          {
   3:              //这是些测试数据
   4:              var listmap = new List<WorkLog>(){
   5:                  new WorkLog{Longitude = "114.433694",Latitude = "30.4503",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "1"},
   6:                  new WorkLog{Longitude = "114.428093",Latitude = "30.448393",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "1"},
   7:                  new WorkLog{Longitude = "114.431075",Latitude = "30.442678",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "3"},
   8:                  new WorkLog{Longitude = "114.443041",Latitude = "30.454072",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "4"},
   9:                  new WorkLog{Longitude = "114.430464",Latitude = "30.456921",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "4"},
  10:                  new WorkLog{Longitude = "114.435951",Latitude = "30.455818",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "4"},
  11:                  new WorkLog{Longitude = "114.421248",Latitude = "30.458477",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "7"},
  12:                  new WorkLog{Longitude = "114.440058",Latitude = "30.44358",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "8"},
  13:                  new WorkLog{Longitude = "114.429225",Latitude = "30.439984",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "9"},
  14:                  new WorkLog{Longitude = "114.425524",Latitude = "30.45099",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "10"},
  15:                  new WorkLog{Longitude = "114.431668",Latitude = "30.448764",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "11"},
  16:                  new WorkLog{Longitude = "114.435693",Latitude = "30.449667",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "12"},
  17:                  new WorkLog{Longitude = "114.436878",Latitude = "30.450165",ContentValue = http://www.mamicode.com/"这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "13"}
  18:              };
  19:   
  20:              StringBuilder str = new StringBuilder();
  21:              foreach (WorkLog wl in listmap)
  22:              {
  23:                  str.Append(string.Format("{0},{1},{2},{3},{4};", wl.Longitude, wl.Latitude, wl.ContentValue, wl.ReportTime,wl.StudentId));
  24:              }
  25:              return Json(str.ToString(), JsonRequestBehavior.AllowGet);
  26:          }
  27:   
  28:          public ActionResult Index()
  29:          {
  30:              return View();
  31:              
  32:          }
<style></style>

因为这里只是一个测试,我直接将一些数据写上去了,没有从数据库中读取。

如果有更多的项目需要,还可以在继续看它的API。

声明:


本篇博客属于原创,允许转载,但是必须注明原文的地址!!