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

摘要:
v=2.0&divide=“container”style=“85%;map=newBMap.map(“container“);zoom);map.addControl(newBMap.NavigationControl());function(data){_initCom(data);function_initCom(data){CommunityList.length=0;

废话先:


这个项目是使用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="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();
        });
    }

这是我一段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;
                    }
                }
            });
        }
    }

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

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

   1:   
   2:  <script type="text/javascript" src="http://t.zoukankan.com/http://api.map.baidu.com/api?v=2.0&ak=your_ak"></script>
   3:  <div id="container" style="85%;height:100%;float:left;border-right:2px solid #bcbcbc"></div>
   4:   
   5:  <div id="searchResult" style="height:100%;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="150px" />
   9:          <input type="button" value="搜索" onclick="search()" />
  10:          <input type="button" value="刷新地图" 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:                       280,
  70:                      height: 128,
  71:                      title: "<strong>学生信息</strong>"
  72:                  }
  73:                  var _data = 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:                   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>

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

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

   1:  public ActionResult getMapInfo()
   2:          {
   3:              //这是些测试数据
   4:              var listmap = new List<WorkLog>(){
   5:                  new WorkLog{Longitude = "114.433694",Latitude = "30.4503",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "1"},
   6:                  new WorkLog{Longitude = "114.428093",Latitude = "30.448393",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "1"},
   7:                  new WorkLog{Longitude = "114.431075",Latitude = "30.442678",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "3"},
   8:                  new WorkLog{Longitude = "114.443041",Latitude = "30.454072",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "4"},
   9:                  new WorkLog{Longitude = "114.430464",Latitude = "30.456921",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "4"},
  10:                  new WorkLog{Longitude = "114.435951",Latitude = "30.455818",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "4"},
  11:                  new WorkLog{Longitude = "114.421248",Latitude = "30.458477",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "7"},
  12:                  new WorkLog{Longitude = "114.440058",Latitude = "30.44358",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "8"},
  13:                  new WorkLog{Longitude = "114.429225",Latitude = "30.439984",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "9"},
  14:                  new WorkLog{Longitude = "114.425524",Latitude = "30.45099",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "10"},
  15:                  new WorkLog{Longitude = "114.431668",Latitude = "30.448764",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "11"},
  16:                  new WorkLog{Longitude = "114.435693",Latitude = "30.449667",ContentValue = "这是学生提交的信息内容",ReportTime = DateTime.Now.ToLocalTime(),StudentId = "12"},
  17:                  new WorkLog{Longitude = "114.436878",Latitude = "30.450165",ContentValue = "这是学生提交的信息内容",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:          }

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

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

声明:


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

免责声明:文章转载自《百度地图在项目中的使用(JS)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇ubuntu16.04 man 手册中英文切换实操 | Airtest测试微信小程序下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

《Maven实战》笔记-8-构建部署Web项目

  一、Web项目结构 1、显式指定Web项目打包方式为war:   2、默认目录 根据“约定大于配置”的规则,Web项目的类及资源文件默认位置为src/main/java和src/main/resources,测试类和测试资源文件默认位置src/test/java和src/test/resources,Web资源目录位于src/main/webapp。...

批量安装Zabbix_Agent

使用自动化部署工具Ansible批量部署zabbix_agent. 1. 安装Ansible   yum –y install ansible   内网情况下,现在ansible及其依赖的rpm包,添加到yum源进行安装。 2. 主机配置文件   在/etc/ansible中添加主机,主机配置文件为hosts,也可以在ansible.cfg中修改配置  ...

Solr搜索引擎入门知识汇总

1.技术选型,为什么用solr而不用lucene,或者其他检索工具 lucene:需要开发者自己维护索引文件,在多机环境中备份同步索引文件很是麻烦 Lucene本质上是搜索库,不是独立的应用程序。而Solr是。 Lucene专注于搜索底层的建设,而Solr专注于企业应用。 Lucene不负责支撑搜索服务所必须的管理,而Solr负责。 一句话概括Solr:...

移动端触屏滑动事件

移动端触屏滑动的效果其实就是图片轮播,在PC的页面上很好实现,绑定click和mouseover等事件来完成。但是在移动设备上,要实现这种轮播的效果,就需要用到核心的touch事件。处理touch事件能跟踪到屏幕滑动的每根手指。 以下是四种touch事件 touchstart:     //手指放到屏幕上时触发 touchmove:      //手指在屏...

spark+kafka 小案例

(1)下载kafka的jar包 http://kafka.apache.org/downloads spark2.1 支持kafka0.8.2.1以上的jar,我是spark2.0.2,下载的kafka_2.11-0.10.2.0 (2)Consumer代码 package com.sparkstreaming import org.apache.spa...

OpenCV+QT开发环境(一):Windows环境

  最近在学习openCV的开发。在搭建开发环境的时候,着实废了不少功夫,找了大量的文章资料。其实主要的开发还是在linux系统上的openCV,但是为了方便,我还是在windows上也搭建了开发环境,这样在进行简单的程序验证的时候,可以直接在windows下进行,而不需要打开虚拟机或者进入linux系统(如果装了双系统的话)。因为windows下还是有不...