使用百度地图开发,画线时内存溢出

发布于 2022-09-30 23:11:00 字数 30871 浏览 33 评论 0

保存2000个点,然后每次新加点就shift掉头一个,发现浏览器内存一直在涨,能有大神帮忙看下吗,我用定时器将经纬度定时增加了,100ms发一次。399行到408行

<html>

<head>
  <title>百度地图(QQ: 517216493)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <style type="text/css">
    html,
    body {
      font-family: 微软雅黑;
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px;
    }

    .anchorBL {
      opacity: 0;
    }

    #map {
      height: 100%;
      width: 100%;
    }

    ::-webkit-scrollbar {
      width: 0.8em;
    }

    ::-webkit-scrollbar-track {
      background: rgb(241, 241, 241);
    }

    ::-webkit-scrollbar-thumb {
      background: rgb(188, 188, 188);
    }

    #info {
      min-width: 200px;
      /* height: 50px; */
      /* border: 1px solid #e4393c;  */
      /* padding: 10px; */
      z-index: 999;
      position: absolute;
      top: 10;
      right: 10;
      box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
      background: #FFFFFF;
      opacity: 0.8;
      border-radius: 8px;
    }

    .infoUL {
      font-size: 10pt;
      padding-left: 0;
      /* text-align: center; */
      list-style-type: none;
    }

    .infoLI {
      margin: 10px;
      margin-bottom: 10px;
      cursor: pointer;
      color: #e4393c;
    }

    .infoLI.hover {
      color: #1a1a1a;
    }

    .title {
      /* padding-right: 10px; */
      width: 120px;
      display: inline-block;
      /* 对超出内容隐藏 */
      overflow: hidden;
      /* 显示省略符号来代表被修剪的文本 */
      text-overflow: ellipsis;
    }

    .detail {
      width: 80px;
      display: inline-block;
      font-weight: bold;
      text-align: right;
      float: right;
      /* 对超出内容隐藏 */
      overflow: hidden;
      /* 显示省略符号来代表被修剪的文本 */
      text-overflow: ellipsis;
    }

    [v-cloak] {
      display: none;
    }
  </style>
  <script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=9GqzBZjfGqXYXMzdfuRN9AL4B4PHaY6R"></script>
  <!-- <script type="text/javascript" src="http://api.map.baidu.com/library/CurveLine/1.5/src/CurveLine.min.js"></script> -->
  <!-- <script type="text/javascript"
    src="http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js"></script> -->
  <!-- <script type="text/javascript"
    src="http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js"></script> -->
  <!-- <script type="text/javascript"
    src="http://api.map.baidu.com/library/TrackAnimation/src/TrackAnimation_min.js"></script> -->
  <!-- <script type="text/javascript"
    src="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.js"></script> -->
  <!-- <link rel="stylesheet" type="text/css"
    href="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.css" /> -->
  <!-- <script type="text/javascript"
    src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script> -->
  <!-- <link rel="stylesheet" type="text/css"
    href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" /> -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- <script src="gps.js"></script> -->


</head>

<body>
  <div id='map' v-cloak></div>
  <div id="info" v-show="tableShow" v-cloak>
    <ul class="infoUL">
      <li class="infoLI" v-for="(item,idx) in signalListTitle" v-on:click="receiveDataClick('row',idx)"
        :class="idx==index?'hover':''" :key="idx">
        <span :title=item class="title">{{item}}:</span><span :title=signalListdetail[idx]
          class="detail">{{signalListdetail[idx]}}</span>
      </li>
    </ul>
  </div>
</body>
<script type="text/javascript">
  var GPS = {
    PI: 3.14159265358979324,
    x_pi: 3.14159265358979324 * 3000.0 / 180.0,
    delta: function (lat, lon) {
      // Krasovsky 1940
      //
      // a = 6378245.0, 1/f = 298.3
      // b = a * (1 - f)
      // ee = (a^2 - b^2) / a^2;
      var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
      var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
      var dLat = GPS.transformLat(lon - 105.0, lat - 35.0);
      var dLon = GPS.transformLon(lon - 105.0, lat - 35.0);
      var radLat = lat / 180.0 * GPS.PI;
      var magic = Math.sin(radLat);
      magic = 1 - ee * magic * magic;
      var sqrtMagic = Math.sqrt(magic);
      dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * GPS.PI);
      dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * GPS.PI);
      return { 'lat': dLat, 'lon': dLon };
    },

    //WGS-84 to GCJ-02
    gcj_encrypt: function (wgsLat, wgsLon) {
      // 31.000, 119.000
      if (GPS.outOfChina(wgsLat, wgsLon)) {
        return { 'lat': wgsLat, 'lon': wgsLon };
      }

      var d = GPS.delta(wgsLat, wgsLon);
      return { 'lat': wgsLat + d.lat, 'lon': wgsLon + d.lon };
    },
    //GCJ-02 to WGS-84
    gcj_decrypt: function (gcjLat, gcjLon) {
      if (GPS.outOfChina(gcjLat, gcjLon))
        return { 'lat': gcjLat, 'lon': gcjLon };

      var d = GPS.delta(gcjLat, gcjLon);
      return { 'lat': gcjLat - d.lat, 'lon': gcjLon - d.lon };
    },
    //GCJ-02 to WGS-84 exactly
    gcj_decrypt_exact: function (gcjLat, gcjLon) {
      var initDelta = 0.01;
      var threshold = 0.000000001;
      var dLat = initDelta, dLon = initDelta;
      var mLat = gcjLat - dLat, mLon = gcjLon - dLon;
      var pLat = gcjLat + dLat, pLon = gcjLon + dLon;
      var wgsLat, wgsLon, i = 0;
      while (1) {
        wgsLat = (mLat + pLat) / 2;
        wgsLon = (mLon + pLon) / 2;
        var tmp = GPS.gcj_encrypt(wgsLat, wgsLon)
        dLat = tmp.lat - gcjLat;
        dLon = tmp.lon - gcjLon;
        if ((Math.abs(dLat) < threshold) && (Math.abs(dLon) < threshold))
          break;

        if (dLat > 0) pLat = wgsLat; else mLat = wgsLat;
        if (dLon > 0) pLon = wgsLon; else mLon = wgsLon;

        if (++i > 10000) break;
      }
      //console.log(i);
      return { 'lat': wgsLat, 'lon': wgsLon };
    },
    //GCJ-02 to BD-09
    bd_encrypt: function (gcjLat, gcjLon) {
      //console.log(JSON.stringify(arguments))
      var x = gcjLon, y = gcjLat;
      var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * GPS.x_pi);
      var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * GPS.x_pi);
      var bdLon = z * Math.cos(theta) + 0.0065;
      var bdLat = z * Math.sin(theta) + 0.006;
      return { 'lat': bdLat, 'lon': bdLon };
    },
    //BD-09 to GCJ-02
    bd_decrypt: function (bdLat, bdLon) {
      var x = bdLon - 0.0065, y = bdLat - 0.006;
      var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * GPS.x_pi);
      var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * GPS.x_pi);
      var gcjLon = z * Math.cos(theta);
      var gcjLat = z * Math.sin(theta);
      return { 'lat': gcjLat, 'lon': gcjLon };
    },
    //WGS-84 to Web mercator
    //mercatorLat -> y mercatorLon -> x
    mercator_encrypt: function (wgsLat, wgsLon) {
      var x = wgsLon * 20037508.34 / 180.;
      var y = Math.log(Math.tan((90. + wgsLat) * GPS.PI / 360.)) / (GPS.PI / 180.);
      y = y * 20037508.34 / 180.;
      return { 'lat': y, 'lon': x };
      /*
      if ((Math.abs(wgsLon) > 180 || Math.abs(wgsLat) > 90))
          return null;
      var x = 6378137.0 * wgsLon * 0.017453292519943295;
      var a = wgsLat * 0.017453292519943295;
      var y = 3189068.5 * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)));
      return {'lat' : y, 'lon' : x};
      //*/
    },
    // Web mercator to WGS-84
    // mercatorLat -> y mercatorLon -> x
    mercator_decrypt: function (mercatorLat, mercatorLon) {
      var x = mercatorLon / 20037508.34 * 180.;
      var y = mercatorLat / 20037508.34 * 180.;
      y = 180 / GPS.PI * (2 * Math.atan(Math.exp(y * GPS.PI / 180.)) - GPS.PI / 2);
      return { 'lat': y, 'lon': x };
      /*
      if (Math.abs(mercatorLon) < 180 && Math.abs(mercatorLat) < 90)
          return null;
      if ((Math.abs(mercatorLon) > 20037508.3427892) || (Math.abs(mercatorLat) > 20037508.3427892))
          return null;
      var a = mercatorLon / 6378137.0 * 57.295779513082323;
      var x = a - (Math.floor(((a + 180.0) / 360.0)) * 360.0);
      var y = (1.5707963267948966 - (2.0 * Math.atan(Math.exp((-1.0 * mercatorLat) / 6378137.0)))) * 57.295779513082323;
      return {'lat' : y, 'lon' : x};
      //*/
    },
    // two point's distance
    distance: function (latA, lonA, latB, lonB) {
      // var earthR = 6371000.;
      // var x = Math.cos(latA * GPS.PI / 180.) * Math.cos(latB * GPS.PI / 180.) * Math.cos((lonA - lonB) * GPS.PI / 180);
      // var y = Math.sin(latA * GPS.PI / 180.) * Math.sin(latB * GPS.PI / 180.);
      // var s = x + y;
      // if (s > 1) s = 1;
      // if (s < -1) s = -1;
      // var alpha = Math.acos(s);
      // var distance = alpha * earthR;
      // return distance;
      var radLat1 = latA * Math.PI / 180.0;
      var radLat2 = latB * Math.PI / 180.0;
      var a = radLat1 - radLat2;
      var b = lonA * Math.PI / 180.0 - lonB * Math.PI / 180.0;
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137;// EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000;
      return s;
    },
    outOfChina: function (lat, lon) {
      if (lon < 72.004 || lon > 137.8347) return true;
      if (lat < 0.8293 || lat > 55.8271) return true;
      return false;
    },
    transformLat: function (x, y) {
      var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
      ret += (20.0 * Math.sin(6.0 * x * GPS.PI) + 20.0 * Math.sin(2.0 * x * GPS.PI)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(y * GPS.PI) + 40.0 * Math.sin(y / 3.0 * GPS.PI)) * 2.0 / 3.0;
      ret += (160.0 * Math.sin(y / 12.0 * GPS.PI) + 320 * Math.sin(y * GPS.PI / 30.0)) * 2.0 / 3.0;
      return ret;
    },
    transformLon: function (x, y) {
      var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
      ret += (20.0 * Math.sin(6.0 * x * GPS.PI) + 20.0 * Math.sin(2.0 * x * GPS.PI)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(x * GPS.PI) + 40.0 * Math.sin(x / 3.0 * GPS.PI)) * 2.0 / 3.0;
      ret += (150.0 * Math.sin(x / 12.0 * GPS.PI) + 300.0 * Math.sin(x / 30.0 * GPS.PI)) * 2.0 / 3.0;
      return ret;
    },
    getLocation: function (callback) {
      var aMap = api.require('aMap');
      aMap.open({
        rect: {
          x: 0,
          y: 0,
          w: 0,
          h: 0
        },
        showUserLocation: true,
        zoomLevel: 11,
        fixed: true
      }, function (ret, err) {
        if (ret.status) {
          aMap.getLocation(function (ret, err) {
            if (ret) {
              if (ret.status) {
                callback(ret);
              } else {
                // alert(JSON.stringify(err));
              }
            } else {
              // alert(JSON.stringify(err))
            }
            aMap.close();
          });
          // alert(JSON.stringify(ret));
        } else {
          // alert(JSON.stringify(err));
        }
      });
    }
  }
  var marker;
  var markerReady;
  var polyLineNow;
  var size = new BMap.Size(20, 20);
  var icon = new BMap.Icon("img/point.svg", size, { imageSize: new BMap.Size(20, 20) });
  function receiveData(type, data) {
    //console.log(JSON.stringify(arguments));
    objName_receiveData(type, data);
  }
  var mapObj = new Vue({
    el: "#map",
    data: {
      location: {
        lng: "121.6488188",
        lat: "31.2306319",
      },
      dragPoint: {
        lng: "121.6488188",
        lat: "31.2306319",
      },
      zoomStatus: undefined,
      center: true,
      IsShowTargetLineStatus: false,
      tableShow: false,
      nowLocationArr: [],
      isShowNowLine: true,
      polyLine: undefined,
      polyLineNow: undefined
    },
    methods: {},
    watch: {
      'location': {
        handler: function (newVal, oldVal) {
          if (this.center == true) {
            var point = null;
             point = new BMap.Point(this.location.lng, this.location.lat);
            //实时显示位置
            map.setCenter(point);
          }
          if (marker != undefined) {
            var point = null;
             point = new BMap.Point(this.location.lng, this.location.lat);
            map.removeOverlay(marker);

          }
          map.setZoom(17);
          var point = null;
           point = new BMap.Point(this.location.lng, this.location.lat);
          marker = null; 
          marker = new BMap.Marker(point);        // 创建标注   
          marker.disableMassClear();
          map.addOverlay(marker);                     // 将标注添加到地图中
          mapObj.nowLocationArr.push(point);

          //判断已走轨迹是否已经超过2000个点
          // if (mapObj.nowLocationArr.length > 2000) {
          //   mapObj.nowLocationArr.shift();
          // }

          //判断地点是否在广德
          // var mapLocation = null;
          //  mapLocation = new BMap.Geocoder();
          // mapLocation.getLocation(point, function (ret) {
          //   if (ret && ret.addressComponents.city == "宣城市") {
          //     map.setMaxZoom(17);
          //   } else {
          //     map.setMaxZoom(22);
          //   }
          // });





          //已走轨迹

          if (mapObj.polyLineNow && mapObj.polyLineNow.Lr != undefined) {
            map.removeOverlay(mapObj.polyLineNow);
          }
          mapObj.polyLineNow = new BMap.Polyline(mapObj.nowLocationArr, { strokeColor: "red", strokeWeight: 3, strokeOpacity: 0.5, strokeStyle: "solid" });
          map.addOverlay(mapObj.polyLineNow);
          if (mapObj.isShowNowLine == true) {
            mapObj.polyLineNow.show();
          } else {
           mapObj.polyLineNow.hide();
          }



          // if (polyLineNow && polyLineNow.Lr != undefined) {
          //   polyLineNow = null;
          //   map.removeOverlay(polyLineNow);
          // }
          // polyLineNow = null;
          // //polyLineNow = new BMap.Polyline(mapObj.nowLocationArr, { strokeColor: "red", strokeWeight: 3, strokeOpacity: 0.5, strokeStyle: "solid" });
          // map.addOverlay(polyLineNow);
          // if (mapObj.isShowNowLine == true) {
          //   polyLineNow.show();
          // } else {
          //   polyLineNow.hide();
          // }




         // addoverlay 一次
         // 500 测shift 


          



        },
        deep: true,
      },
      "dragPoint": {
        handler: function (newVal, oldVal) {
          if (mapObj.center == true) {
            if ((mapObj.dragPoint.lng != mapObj.location.lng) || (mapObj.dragPoint.lat != mapObj.location.lat)) {
              //console.log(JSON.stringify(mapObj.dragPoint));
              //console.log(JSON.stringify(mapObj.location));

              var point = new BMap.Point(this.location.lng, this.location.lat);
              //console.log(JSON.stringify(point));
              //实时显示位置
              setTimeout(() => {
                map.setCenter(point);
              }, 200)
            }
          }
        },
        deep: true
      },
      "zoomStatus": {
        handler: function (newVal, oldVal) {
          if (mapObj.center == true) {
            //console.log(JSON.stringify(mapObj.dragPoint));
            //console.log(JSON.stringify(mapObj.location));
            var point = new BMap.Point(this.location.lng, this.location.lat);
            //console.log(JSON.stringify(point));
            //实时显示位置
            setTimeout(() => {
              map.setCenter(point);
            }, 200)
          }
        },
        deep: true
      },
    },
  });
  var info = new Vue({
    el: "#info",
    data: {
      tableShow: false,
      tableOrign: "",
      signalListTitle: [],
      signalListdetail: [],
      index: undefined,
    },
    methods: {
      receiveDataClick: function (type, data) {
        if ((this.index == data) && (this.index != undefined)) {
          //console.log(type, data);
          this.index = undefined;
          receiveData("row", "-1");
          return;
        } else {
          //console.log(type, data);
          receiveData("row", String(data));
        }
        this.index = data;
      }
    },
    watch: {
      'tableOrign': {
        handler: function (newVal, oldVal) {
          if (oldVal == "") {
            //alert("11111")
            showSignal(true);
          }
          //console.log("hahaha",newVal)

          var signalTotal = this.tableOrign.split(";");
          var oldLen = oldVal.split(";").length;
          var newLen = newVal.split(";").length;
          if (newLen != oldLen) {
            info.index = undefined;
          }
          info.signalListTitle = [];
          info.signalListdetail = [];
          for (var i = 0; i < signalTotal.length; i++) {
            info.signalListTitle.push(signalTotal[i].split(",")[0]);
            info.signalListdetail.push(signalTotal[i].split(",")[1]);
          }
        },
        deep: true,
      },

    },
  });
  var map = new BMap.Map('map', { minZoom: 4, maxZoom: 17, enableMapClick: false, showZoomControls: false, mapType: BMAP_SATELLITE_MAP });
  map.addEventListener("dragend", function (evt) {
    //console.log(JSON.stringify(evt.point));
    mapObj.dragPoint = evt.point;
  });
  map.addEventListener("zoomend", function (evt) {
    //alert(map.getZoom());
    mapObj.zoomStatus = map.getZoom();

    //console.log(JSON.stringify(e));

  });
  map.setZoom(17);


  window.onresize = function () {
    if(mapObj.center == true){
      setTimeout(()=>{
        setCenter(true);
      },200);}

  }




  //传经纬度
  function getLocation(lat, lon) {
    //mapObj.location.lat = lat;//纬度
    //mapObj.location.lng = lng;//经度
    //纠偏
    //var realLocGD = GPS.gcj_encrypt(lat, lon);
    //alert(JSON.stringify(realLocGD));

    //var realLocBD = GPS.bd_encrypt(realLocGD.lat, realLocGD.lon);
    function translateCallback(data) {
      mapObj.location.lat = data.points[0].lat;
      mapObj.location.lng = data.points[0].lng;
      //console.log(mapObj.nowLocationArr);
    }

    var ggPoint = new BMap.Point(lon, lat);
    //console.log(ggPoint);
    var convertor = new BMap.Convertor();
    var pointArr = [];
    pointArr.push(ggPoint);
    //console.log(JSON.stringify(pointArr));
    convertor.translate(pointArr, 1, 5, translateCallback)


    if (mapObj.center == true) {
      var point = new BMap.Point(mapObj.location.lng, mapObj.location.lat);
      //实时显示位置
      map.setCenter(point);
    }


    //console.log(JSON.stringify( realLoc));
    //console.log(lat,lng);

  };

  //居中
  function setCenter(ret) {
    if (ret == true) {
      mapObj.center = true;
      var point = new BMap.Point(mapObj.location.lng, mapObj.location.lat);
      //console.log(JSON.stringify(point));
      //实时显示位置
      map.setCenter(point);

    } else {
      mapObj.center = false;
    }
  }

  //传轨迹点
  function showTargetLine(ret) {
    if (ret == undefined) {
      return
    }

    //更新目标轨迹
    if (mapObj.polyLine != "") {
      map.clearOverlays();
    }

    //轨迹点纠偏
    var ggPoints = [];
    var rets = ret.split(";");
    //console.log(rets);
    //alert(JSON.stringify(rets.length));

    for (var i = 0; i < rets.length; i++) {
      var lng = Number(rets[i].split(",")[0]);
      var lat = Number(rets[i].split(",")[1]);
      //console.log(lng,lat);
      var locationGCJ = GPS.gcj_encrypt(lat, lng);
      var locationGBD = GPS.bd_encrypt(locationGCJ.lat, locationGCJ.lon);
      //console.log(JSON.stringify(locationGBD))

      ggPoints.push(new BMap.Point(locationGBD.lon, locationGBD.lat));
    };
    //console.log(ggPoints);
    //mapObj.polyLine = "1";
    //ggPoints.length = 10
    mapObj.polyLine = new BMap.Polyline(ggPoints, { strokeColor: "blue", strokeWeight: 2, strokeOpacity: 1 });
    map.addOverlay(mapObj.polyLine);

  }

  //是否显示目标轨迹
  function IsShowTargetLine(ret) {
    //true 画轨迹 ; false 清除轨迹
    if (ret) {
      mapObj.IsShowTargetLineStatus = true;
      mapObj.polyLine && mapObj.polyLine.show();
    } else {
      mapObj.IsShowTargetLineStatus = false;
      mapObj.polyLine && mapObj.polyLine.hide();
    }
  }

  //是否显示信号
  function showSignal(ret) {
    //alert(ret + JSON.stringify(info.tableOrign))
    if (ret && info.tableOrign != "") {
      info.tableShow = true
    } else {
      info.tableShow = false
    }
  }

  //信号数据
  function setSignalValue(ret) {
    //alert(JSON.stringify(ret));
    if (ret != "") {
      info.tableOrign = ret;
    } else {
      info.signalListTitle = [];
      info.signalListdetail = [];
      info.tableShow = false;
      info.tableOrign = ''

    }
  }

  //是否显示当前已走轨迹
  function isShowNowLine(ret) {
    if (ret) {

      mapObj.isShowNowLine = true;

      mapObj.polyLineNow.show();
      //map.addOverlay(mapObj.polyLineNow);

    } else {

      // alert(JSON.stringify(ret));
      //console.log(mapObj.nowLocationArr)   
      mapObj.isShowNowLine = false;
      mapObj.nowLocationArr = [];
      map.removeOverlay(mapObj.polyLineNow);
      // console.log( mapObj.nowLocationArr)
      // map.removeOverlay(mapObj.polyLineNow);
      //manObj.polyLineNow = undefined;
      mapObj.polyLineNow.hide();
    }
  };

   //lng: "121.6488188",
    //    lat: "31.2306319",

        let xx  = 121.6488188;
        let  yy = 31.2306319;

        function lala() {
          xx = xx+0.00001;
          yy = yy+0.00001;
          mapObj.location.lat = yy;
          mapObj.location.lng = xx;
        }

        setInterval("lala()",100);





  


  




  var point = new BMap.Point(121.424362, 31.175942);
  map.centerAndZoom(point, 11);
  map.enableDragging(true);
  map.enableScrollWheelZoom(true);
  // map.enableDoubleClickZoom(true);
  map.enableKeyboard(false);
  // map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE }));
  map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP], anchor: BMAP_ANCHOR_TOP_LEFT }));
  //var ctrlTra = new BMapLib.TrafficControl({ showPanel: false });
  //ctrlTra.setAnchor(BMAP_ANCHOR_BOTTOM_RIGHT);
  //map.addControl(ctrlTra);
  function getPoints(points) {
    var pts = []
    var listPoint = points.split('|');
    var len = listPoint.length
    for (var i = 0; i < len; i++) {
      var list = listPoint[i].split(',');
      var pot = new BMap.Point(list[0], list[1]);
      pts.push(pot);
    }
    return pts;
  }
  function getMarkers(points) {
    var markers = []
    var listPoint = points.split('|');
    var len = listPoint.length
    for (var i = 0; i < len; i++) {
      var list = listPoint[i].split(',');
      var pot = new BMap.Point(list[0], list[1]);
      var marker = new BMap.Marker(pot);
      markers.push(marker);
    }
    return markers;
  }
  function getBounds() {
    var bs = map.getBounds();
    var bssw = bs.getSouthWest();
    var bsne = bs.getNorthEast();
    var bsce = bs.getCenter();
    var rect = bssw.lng + ',' + bssw.lat + ',' + bsne.lng + ',' + bsne.lat + ',' + bsce.lng + ',' + bsce.lat + ',' + map.getZoom();
    receiveData('bounds', rect);
  }
  function getBoundary() {
    for (var i = 0; i < polygons.length; i++) {
      var polyline = polygons[i];
      var pts = polyline.getPath();
      var result = '';
      for (var j = 0; j < pts.length; j++) {
        result += pts[j].lng + ',' + pts[j].lat + ';';
      }
      receiveData('newboundary', result);
    }
  }
  function getZoom() {
    var zoom = map.getZoom();
    receiveData('zoom', zoom);
  }
  var geo = new BMap.Geocoder();
  function getPointByAddr(addr) {
    geo.getPoint(addr, function (result) {
      if (result) {
        receiveData('geocoder', result.lng + ',' + result.lat);
      }
    });
  }
  function getAddrByPoint(point) {
    var list = point.split(',');
    var pot = new BMap.Point(list[0], list[1]);
    geo.getLocation(pot, function (result) {
      if (result) {
        receiveData('geocoder', result.address);
      }
    });
  }
  function addClick(marker, name, addr, title, tips, width, action) {
    if (title == '' && name != '') {
      title = '<div style="color:#CE5521;font-size:15px;">' + name + '</div>';
    }
    if (tips == '' && addr != '') {
      tips = '<table><tr style="vertical-align:top;line-height:25px;font-size:12px;"><td>地址:</td><td>' + addr + '</td></tr></table>';
    }
    var infoWindow = new BMap.InfoWindow(tips, { title: title, width: width });
    var markerClick = function () {
      if (action == 1) {
        marker.openInfoWindow(infoWindow);
      } else if (action == 2) {
        receiveData('marker', '名称: ' + name + '  地址: ' + addr);
      }
    };
    marker.addEventListener('click', markerClick);
  }
  function addMarker(name, addr, title, tips, width, point, action, animation, iconfile, iconindex) {
    alert(123); var list = point.split(',');
    var pot = new BMap.Point(list[0], list[1]);
    var label = new BMap.Label(name, { "offset": new BMap.Size(20, -10) });
    if (!iconfile) {
      var marker = new BMap.Marker(pot);
    } else if (iconfile == 'http://lbsyun.baidu.com/jsdemo/img/fox.gif') {
      var icon = new BMap.Icon(iconfile, new BMap.Size(300, 157));
      var marker = new BMap.Marker(pot, { icon: icon });
    } else if (iconfile == 'http://api.map.baidu.com/img/markers.png') {
      var icon = new BMap.Icon(iconfile, new BMap.Size(23, 25), { offset: new BMap.Size(10, 25), imageOffset: new BMap.Size(0, 0 - iconindex * 25) });
      var marker = new BMap.Marker(pot, { icon: icon });
    } else {
      var icon = new BMap.Icon(iconfile, new BMap.Size(53, 52));
      var marker = new BMap.Marker(pot, { icon: icon });
    }
    map.addOverlay(marker);
    if (name != '') {
      marker.setLabel(label);
    }
    addClick(marker, name, addr, title, tips, width, action);
    if (animation == 1) {
      marker.setAnimation(BMAP_ANIMATION_BOUNCE);
    } else if (animation == 2) {
      marker.setAnimation(BMAP_ANIMATION_DROP);
    }
  }
  function deleteMarker(name) {
    var allOverlay = map.getOverlays();
    var len = allOverlay.length;
    for (var i = 0; i < len; i++) {
      var overlay = allOverlay[i];
      if (overlay.toString() != '[object Marker]') {
        continue;
      }
      if (name.length == 0) {
        map.removeOverlay(overlay);
      } else {
        var label = overlay.getLabel();
        if (label == null) {
          continue;
        }
        if (label.content == name) {
          map.removeOverlay(allOverlay[i]);
          break;
        }
      }
    }
  }
  function deleteOverlay(type) {
    var allOverlay = map.getOverlays();
    var len = allOverlay.length;
    for (var i = 0; i < len; i++) {
      var overlay = allOverlay[i];
      if (type.length == 0) {
        map.removeOverlay(overlay);
      } else {
        var strType = '[object ' + type + ']'
        if (overlay.toString() == strType) {
          map.removeOverlay(overlay);
        }
      }
    }
  }
  function addPolyline(points) {
    var pts = getPoints(points);
    var polyline = new BMap.Polyline(pts, { strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.5 });
    map.addOverlay(polyline);
  }
  function addPolygon(points) {
    var pts = getPoints(points);
    var polygon = new BMap.Polygon(pts, { strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.5 });
    map.addOverlay(polygon);
  }
  function addRectangle(points) {
    var listPoint = points.split('|');
    if (listPoint.length != 2) {
      return;
    }
    var list1 = listPoint[0].split(',');
    var list2 = listPoint[1].split(',');
    var ptStart = new BMap.Point(list1[0], list1[1]);
    var ptEnd = new BMap.Point(list2[0], list2[1]);
    var pt1 = new BMap.Point(ptStart.lng, ptStart.lat);
    var pt2 = new BMap.Point(ptEnd.lng, ptStart.lat);
    var pt3 = new BMap.Point(ptEnd.lng, ptEnd.lat);
    var pt4 = new BMap.Point(ptStart.lng, ptEnd.lat);
    var rectangle = new BMap.Polygon([pt1, pt2, pt3, pt4], { strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.5 });
    map.addOverlay(rectangle);
  }
  function addCircle(points, radius) {
    var listPoint = points.split('|');
    var list = listPoint[0].split(',');
    var ptCenter = new BMap.Point(list[0], list[1]);
    var circle = new BMap.Circle(ptCenter, radius, { strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.5 });
    map.addOverlay(circle);
  }
  function addCurveLine(points) {
    var pts = getPoints(points);
    var curveLine = new BMapLib.CurveLine(pts, { strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.5 });
    map.addOverlay(curveLine);
    curveLine.enableEditing();
  }
  var polygons = [];
  function addBoundary(cityname, callfun, edit) {
    map.clearOverlays();
    var bdary = new BMap.Boundary();
    bdary.get(cityname, function (rs) {
      var count = rs.boundaries.length;
      if (count > 0) {
        if (callfun) {
          receiveData('boundary', rs.boundaries);
        }
        var pointArray = [];
        for (var i = 0; i < count; i++) {
          var ply = new BMap.Polygon(rs.boundaries[i], { strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.5 });
          if (edit) {
            ply.enableEditing();
          }
          polygons.push(ply);
          map.addOverlay(ply);
          pointArray = pointArray.concat(ply.getPath());
        }
        map.setViewport(pointArray);
      }
    });
  }
  function addMarkerClusterer(points) {
    alert(123); var markers = getMarkers(points);
    var markerClusterer = new BMapLib.MarkerClusterer(map, { markers: markers });
  }
  var overlays = [];
  var overlaycomplete = function (e) {
    overlays.push(e.overlay);
  };
  var styleOptions = {
    strokeColor: "red",
    fillColor: "red",
    strokeWeight: 3,
    strokeOpacity: 0.8,
    fillOpacity: 0.6,
    strokeStyle: 'solid'
  }

  function clearAll() {
    for (var i = 0; i < overlays.length; i++) {
      map.removeOverlay(overlays[i]);
    }
    overlays.length = 0;
  }
</script>

</html>


<!-- "121.65102530,31.23234760"
"121.65164430,31.23264980"
"121.65164200,31.23264920"
"121.65163970,31.23264860"
"121.65161010,31.23264090"
"121.65160780,31.23264030"
"121.65160560,31.23263970"
"121.65160330,31.23263910" -->

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文