当前位置:首页 > JSP教程 > JSP常见问题

js实现百度地图同时显示多个路书效果

本文介绍了js实现百度地图同时显示多个路书效果,主要是以自行车的还车地点作为实例,具体代码如下:

启动路书:

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=自己的ak"></script>
<script type="text/javascript" src="js/lushu.js"></script><!--路书 -->
var bmaplib = window.bmaplib = bmaplib || {};
(function() {
  var b, a = b = a || {
    version : "1.5.0"
  };
  a.guid = "$baidu$";
  (function() {
    window[a.guid] = window[a.guid] || {};
    a.dom = a.dom || {};
    a.dom.g = function(e) {
      if ("string" == typeof e || e instanceof string) {
        return document.getelementbyid(e)
      } else {
        if (e && e.nodename && (e.nodetype == 1 || e.nodetype == 9)) {
          return e
        }
      }
      return null
    };
    a.g = a.g = a.dom.g;
    a.lang = a.lang || {};
    a.lang.isstring = function(e) {
      return "[object string]" == object.prototype.tostring.call(e)
    };
    a.isstring = a.lang.isstring;
    a.dom._g = function(e) {
      if (a.lang.isstring(e)) {
        return document.getelementbyid(e)
      }
      return e
    };
    a._g = a.dom._g;
    a.dom.getdocument = function(e) {
      e = a.dom.g(e);
      return e.nodetype == 9 ? e : e.ownerdocument || e.document
    };
    a.browser = a.browser || {};
    a.browser.ie = a.ie = /msie (d+.d+)/i.test(navigator.useragent) ? (document.documentmode || +regexp["x241"])
        : undefined;
    a.dom.getcomputedstyle = function(f, e) {
      f = a.dom._g(f);
      var h = a.dom.getdocument(f), g;
      if (h.defaultview && h.defaultview.getcomputedstyle) {
        g = h.defaultview.getcomputedstyle(f, null);
        if (g) {
          return g[e] || g.getpropertyvalue(e)
        }
      }
      return ""
    };
    a.dom._stylefixer = a.dom._stylefixer || {};
    a.dom._stylefilter = a.dom._stylefilter || [];
    a.dom._stylefilter.filter = function(f, j, k) {
      for (var e = 0, h = a.dom._stylefilter, g; g = h[e]; e++) {
        if (g = g[k]) {
          j = g(f, j)
        }
      }
      return j
    };
    a.string = a.string || {};
    a.string.tocamelcase = function(e) {
      if (e.indexof("-") < 0 && e.indexof("_") < 0) {
        return e
      }
      return e.replace(/[-_][^-_]/g, function(f) {
        return f.charat(1).touppercase()
      })
    };
    a.dom.getstyle = function(g, f) {
      var i = a.dom;
      g = i.g(g);
      f = a.string.tocamelcase(f);
      var h = g.style[f] || (g.currentstyle ? g.currentstyle[f] : "")
          || i.getcomputedstyle(g, f);
      if (!h) {
        var e = i._stylefixer[f];
        if (e) {
          h = e.get ? e.get(g) : a.dom.getstyle(g, e)
        }
      }
      if (e = i._stylefilter) {
        h = e.filter(f, h, "get")
      }
      return h
    };
    a.getstyle = a.dom.getstyle;
    a.dom._name_attrs = (function() {
      var e = {
        cellpadding : "cellpadding",
        cellspacing : "cellspacing",
        colspan : "colspan",
        rowspan : "rowspan",
        valign : "valign",
        usemap : "usemap",
        frameborder : "frameborder"
      };
      if (a.browser.ie < 8) {
        e["for"] = "htmlfor";
        e["class"] = "classname"
      } else {
        e.htmlfor = "for";
        e.classname = "class"
      }
      return e
    })();
    a.dom.setattr = function(f, e, g) {
      f = a.dom.g(f);
      if ("style" == e) {
        f.style.csstext = g
      } else {
        e = a.dom._name_attrs[e] || e;
        f.setattribute(e, g)
      }
      return f
    };
    a.setattr = a.dom.setattr;
    a.dom.setattrs = function(g, e) {
      g = a.dom.g(g);
      for ( var f in e) {
        a.dom.setattr(g, f, e[f])
      }
      return g
    };
    a.setattrs = a.dom.setattrs;
    a.dom.create = function(g, e) {
      var h = document.createelement(g), f = e || {};
      return a.dom.setattrs(h, f)
    };
    a.object = a.object || {};
    a.extend = a.object.extend = function(g, e) {
      for ( var f in e) {
        if (e.hasownproperty(f)) {
          g[f] = e[f]
        }
      }
      return g
    }
  })();
  var c = bmaplib.lushu = function(g, f, e) {
    if (!f || f.length < 1) {
      return
    }
    this._map = g;
    this._path = f;
    this.i = 0;
    this._settimeoutquene = [];
    this._projection = this._map.getmaptype().getprojection();
    this._opts = {
      icon : null,
      speed : 4000,
      defaultcontent : ""
    };
    this._setoptions(e);
    this._rotation = 0;
    if (!this._opts.icon instanceof bmap.icon) {
      this._opts.icon = defaulticon
    }
  };
  c.prototype._setoptions = function(e) {
    if (!e) {
      return
    }
    for ( var f in e) {
      if (e.hasownproperty(f)) {
        this._opts[f] = e[f]
      }
    }
  };
  c.prototype.start = function() {
    var f = this, e = f._path.length;
    if (f.i && f.i < e - 1) {
      if (!f._frompause) {
        return
      } else {
        if (!f._fromstop) {
          f._movenext(++f.i)
        }
      }
    } else {
      f._addmarker();
      f._timeoutflag = settimeout(function() {
        f._addinfowin();
        if (f._opts.defaultcontent == "") {
          f.hideinfowindow()
        }
        f._movenext(f.i)
      }, 400)
    }
    this._frompause = false;
    this._fromstop = false
  }, c.prototype.stop = function() {
    this.i = 0;
    this._fromstop = true;
    clearinterval(this._intervalflag);
    this._cleartimeout();
    for (var g = 0, f = this._opts.landmarkpois, e = f.length; g < e; g++) {
      f[g].bshow = false
    }
  };
  c.prototype.pause = function() {
    clearinterval(this._intervalflag);
    this._frompause = true;
    this._cleartimeout()
  };
  c.prototype.hideinfowindow = function() {
    this._overlay._div.style.visibility = "hidden"
  };
  c.prototype.showinfowindow = function() {
    this._overlay._div.style.visibility = "visible"
  };
  a.object
      .extend(
          c.prototype,
          {
            _addmarker : function(f) {
              if (this._marker) {
                this.stop();
                this._map.removeoverlay(this._marker);
                cleartimeout(this._timeoutflag)
              }
              this._overlay
                  && this._map.removeoverlay(this._overlay);
              var e = new bmap.marker(this._path[0]);
              this._opts.icon && e.seticon(this._opts.icon);
              this._map.addoverlay(e);
              e.setanimation(bmap_animation_drop);
              this._marker = e
            },
            _addinfowin : function() {
              var f = this;
              var e = new d(f._marker.getposition(),
                  f._opts.defaultcontent);
              e.setrelatedclass(this);
              this._overlay = e;
              this._map.addoverlay(e)
            },
            _getmercator : function(e) {
              return this._map.getmaptype().getprojection()
                  .lnglattopoint(e)
            },
            _getdistance : function(f, e) {
              return math.sqrt(math.pow(f.x - e.x, 2)
                  + math.pow(f.y - e.y, 2))
            },
            _move : function(n, j, m) {
              var i = this, h = 0, e = 10, f = this._opts.speed
                  / (1000 / e), l = this._projection
                  .lnglattopoint(n), k = this._projection
                  .lnglattopoint(j), g = math.round(i
                  ._getdistance(l, k)
                  / f);
              if (g < 1) {
                i._movenext(++i.i);
                return
              }
              i._intervalflag = setinterval(
                  function() {
                    if (h >= g) {
                      clearinterval(i._intervalflag);
                      if (i.i > i._path.length) {
                        return
                      }
                      i._movenext(++i.i)
                    } else {
                      h++;
                      var o = m(l.x, k.x, h, g), r = m(
                          l.y, k.y, h, g), q = i._projection
                          .pointtolnglat(new bmap.pixel(
                              o, r));
                      if (h == 1) {
                        var p = null;
                        if (i.i - 1 >= 0) {
                          p = i._path[i.i - 1]
                        }
                        if (i._opts.enablerotation == true) {
                          i.setrotation(p, n, j)
                        }
                        if (i._opts.autoview) {
                          if (!i._map.getbounds()
                              .containspoint(q)) {
                            i._map.setcenter(q)
                          }
                        }
                      }
                      i._marker.setposition(q);
                      i._setinfowin(q)
                    }
                  }, e)
            },
            setrotation : function(l, f, m) {
              var j = this;
              var e = 0;
              f = j._map.pointtopixel(f);
              m = j._map.pointtopixel(m);
              if (m.x != f.x) {
                var k = (m.y - f.y) / (m.x - f.x), g = math
                    .atan(k);
                e = g * 360 / (2 * math.pi);
                if (m.x < f.x) {
                  e = -e + 90 + 90
                } else {
                  e = -e
                }
                j._marker.setrotation(-e)
              } else {
                var h = m.y - f.y;
                var i = 0;
                if (h > 0) {
                  i = -1
                } else {
                  i = 1
                }
                j._marker.setrotation(-i * 90)
              }
              return
            },
            linepixellength : function(f, e) {
              return math.sqrt(math.abs(f.x - e.x)
                  * math.abs(f.x - e.x) + math.abs(f.y - e.y)
                  * math.abs(f.y - e.y))
            },
            pointtopoint : function(f, e) {
              return math.abs(f.x - e.x) * math.abs(f.x - e.x)
                  + math.abs(f.y - e.y) * math.abs(f.y - e.y)
            },
            _movenext : function(e) {
              var f = this;
              if (e < this._path.length - 1) {
                f._move(f._path[e], f._path[e + 1],
                    f._tween.linear)
              }
            },
            _setinfowin : function(g) {
              var f = this;
              if (!f._overlay) {
                return
              }
              f._overlay.setposition(g, f._marker.geticon().size);
              var e = f._troughpointindex(g);
              if (e != -1) {
                clearinterval(f._intervalflag);
                f._overlay
                    .sethtml(f._opts.landmarkpois[e].html);
                f._overlay.setposition(g,
                    f._marker.geticon().size);
                f._pauseforview(e)
              } else {
                f._overlay.sethtml(f._opts.defaultcontent)
              }
            },
            _pauseforview : function(e) {
              var g = this;
              var f = settimeout(function() {
                g._movenext(++g.i)
              }, g._opts.landmarkpois[e].pausetime * 1000);
              g._settimeoutquene.push(f)
            },
            _cleartimeout : function() {
              for ( var e in this._settimeoutquene) {
                cleartimeout(this._settimeoutquene[e])
              }
              this._settimeoutquene.length = 0
            },
            _tween : {
              linear : function(f, j, h, i) {
                var e = f, l = j - f, g = h, k = i;
                return l * g / k + e
              }
            },
            _troughpointindex : function(f) {
              var h = this._opts.landmarkpois, j;
              for (var g = 0, e = h.length; g < e; g++) {
                if (!h[g].bshow) {
                  j = this._map.getdistance(new bmap.point(
                      h[g].lng, h[g].lat), f);
                  if (j < 10) {
                    h[g].bshow = true;
                    return g
                  }
                }
              }
              return -1
            }
          });
  function d(e, f) {
    this._point = e;
    this._html = f
  }
  d.prototype = new bmap.overlay();
  d.prototype.initialize = function(e) {
    var f = this._div = a.dom
        .create(
            "div",
            {
              style : "border:solid 1px #ccc;width:auto;min-width:50px;text-align:center;position:absolute;background:#fff;color:#000;font-size:12px;border-radius: 10px;padding:5px;white-space: nowrap;"
            });
    f.innerhtml = this._html;
    e.getpanes().floatpane.appendchild(f);
    this._map = e;
    return f
  };
  d.prototype.draw = function() {
    this.setposition(this.lushumain._marker.getposition(),
        this.lushumain._marker.geticon().size)
  };
  a.object.extend(d.prototype, {
    setposition : function(h, i) {
      var f = this._map.pointtooverlaypixel(h), e = a.dom.getstyle(
          this._div, "width"), g = a.dom
          .getstyle(this._div, "height");
      overlayw = parseint(this._div.clientwidth || e, 10),
          overlayh = parseint(this._div.clientheight || g, 10);
      this._div.style.left = f.x - overlayw / 2 + "px";
      this._div.style.bottom = -(f.y - i.height) + "px"
    },
    sethtml : function(e) {
      this._div.innerhtml = e
    },
    setrelatedclass : function(e) {
      this.lushumain = e
    }
  })
})();
function showallrecord(starttime,endtime){//显示多条开始结束时间之间的自行车路书
  var bikeid=null;
  $.getjson("./getbickidservlet",function(json){
    bikeid = json;//所有自行车编号
  });
  var json={
      "starttime":starttime,//开始时间
      "endtime":endtime//结束时间
  };
  //创建二维数组,例如pointarray[i]中i自行车编号,pointarray[i][j]为编号为i的自行车的所有借还站点信息
  $.getjson("./getallrecordservlet",{json:json.stringify(json)},function(json){
    var j = 0;
    var stationlonlist=new array();
    var stationlatlist=new array();
    var pointarray=new array();
    var bikeidlist = new array();
    for(var i = 0; i < bikeid.length; i++){
      stationlonlist[i] = new array();
      stationlatlist[i] = new array();
      pointarray[i] = new array();
      bikeidlist[i] = bikeid[i].bikeid;
    }
    var tt = json.length < 200?json.length:200;//如果查询出来的自行车借还站点记录多于200条,则显示200条。(待完善)
    for (var row = 0; row < pointarray.length; row++) {
      while (j < tt) {
        var k = j;
        var p = 0;
        var stationlon = parsefloat(json[j].stationlon);// string类型转换成float类型
        stationlonlist[row][p]=stationlon;// 将stationlon放到stationlonlist里
        var stationlat = parsefloat(json[j].stationlat);
        stationlatlist[row][p]=stationlat;// 将stationlat放到stationlatlist里
        pointarray[row][p] = new bmap.point(stationlon,stationlat);
        while (bikeidlist[row] == json[k + 1].bikeid) {
          k++;
          p++;
          stationlon= parsefloat(json[k].stationlon);// string类型转换成float类型
          stationlonlist[row][p]=stationlon;// 将stationlon放到stationlonlist里
          stationlat= parsefloat(json[k].stationlat);
          stationlatlist[row][p] =stationlat;// 将stationlat放到stationlatlist里
          pointarray[row][p] = new bmap.point(stationlon, stationlat);
        }
        addmarkertest(pointarray,row);//添加标记点
        j = k + 1;
        break;
      }
      var bikespeedtest = speedtest(pointarray,row);//每辆自行车路书的速度
      polylinetest(pointarray,row,stationlonlist,stationlatlist);//每辆自行车借还站点间画折线
      lushutest(pointarray,bikespeedtest,row,stationlonlist,stationlatlist);//每辆自行车借还站点的路书路径
    }
    map.setviewport(pointarray);
  });
}

function speedtest(pointarray,row){//根据自行车的借还时间差来显示不同的路书速度(待完善)
  var distance = 0;//直行车走过的路径长度
  for(var i = 0; i < pointarray[row].length-1; i++){
    distance += (map.getdistance(pointarray[row][i],pointarray[row][i+1]));//自行车借还站点的路径长度
  }
  return distance/20;//速度=路径长度/时间(此处时间固定,可改为根据数据库读取的时间)
}

//
function polylinetest(pointarray,row,stationlonlist,stationlatlist){
  var points = new array();
  for(var i = 0; i < pointarray[row].length; i++){
    points[i] = new bmap.point(parsefloat(stationlonlist[row][i]), parsefloat(stationlatlist[row][i]));
  }
  //增加点与点之间的连线
  var polyline = new bmap.polyline(points, {
    strokecolor : getcolor(),
    strokeweight : 2,
    strokeopacity : 0.5
  }); // 创建折线
  map.addoverlay(polyline); // 绘制折线
}

//
function lushutest(pointarray,bikespeedtest,row,stationlonlist,stationlatlist){
  var points = new array();
  for(var i = 0; i < pointarray[row].length; i++){
    points[i] = new bmap.point(parsefloat(stationlonlist[row][i]), parsefloat(stationlatlist[row][i]));
  }
  var lushu = new bmaplib.lushu(map, points, {
    defaultcontent : "",
    autoview : true, // 是否开启自动视野调整,如果开启那么路书在运动过程中会根据视野自动调整
    icon : new bmap.icon('photo/bike.png', new bmap.size(22, 22), {
      anchor : new bmap.size(10, 25)
    }),
    // enablerotation: true, //是否设置marker随着道路的走向进行旋转
    speed : bikespeedtest,
  });  
  lushu.start();
}

//生成折线的随机颜色
function sj16(){
  var sjshu=math.round(math.random()*10*2);
  do
  {
    sjshu=math.round(math.random()*10*2);
  }while (sjshu>=14);
  return sjshu;
}
function getcolor(){
  var hex = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
  var yanse="";
  for(i=0; i<6; i++){
    yanse+=hex[sj16()];
  }
  return "#"+yanse
}

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐