百度地图添加悬浮窗搜索功能

来自:https://www.2cto.com/kf/201701/587448.html 侵删


<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> body, html{ 100%;height: 100%;margin:0;font-family:"微软雅黑";font-size:14px;} #l-map{height:300px;100%;} #r-result{100%;} </style> <!-- <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.4"></script> --> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=密匙"></script> <title>关键字输入提示词条</title> </head> <body> <p id="l-map"> </p> </body> </html> <script type="text/javascript"> // 百度地图API功能 function G(id) { return document.getElementById(id); } var map = new BMap.Map("l-map"); map.centerAndZoom(new BMap.Point(120.714537, 30.122469), 9); // 初始化地图,设置城市和地图级别。 // 定义一个控件类,即function function ZoomControl() { this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT; this.defaultOffset = new BMap.Size(10, 10); } // 通过JavaScript的prototype属性继承于BMap.Control ZoomControl.prototype = new BMap.Control(); // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回 // 在本方法中创建个p元素作为控件的容器,并将其添加到地图容器中 ZoomControl.prototype.initialize = function(map){ // 创建一个DOM元素 var p = document.createElement("p"); p.innerHTML = '<p id="r-result">搜索地址:<input type="text" id="suggestId" size="20" value="百度" style="150px;" /></p><p id="searchResultPanel" style="border:1px solid #C0C0C0;150px;height:auto; display:none;"></p>'; // 添加DOM元素到地图中 map.getContainer().appendChild(p); // 将DOM元素返回 return p; } // 创建控件 var myZoomCtrl = new ZoomControl(); // 添加到地图当中 map.addControl(myZoomCtrl); var ac = new BMap.Autocomplete( //建立一个自动完成的对象 {"input" : "suggestId" ,"location" : map }); ac.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件 var str = ""; var _value = e.fromitem.value; var value = ""; if (e.fromitem.index > -1) { value = _value.province + _value.city + _value.district + _value.street + _value.business; } str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value; value = ""; if (e.toitem.index > -1) { _value = e.toitem.value; value = _value.province + _value.city + _value.district + _value.street + _value.business; } str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value; G("searchResultPanel").innerHTML = str; }); var myValue; ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件 var _value = e.item.value; myValue = _value.province + _value.city + _value.district + _value.street + _value.business; G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue; setPlace(); }); function setPlace(){ map.clearOverlays(); //清除地图上所有覆盖物 function myFun(){ var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果 map.centerAndZoom(pp, 14); console.log('pp',pp) map.addOverlay(new BMap.Marker(pp)); //添加标注 } var local = new BMap.LocalSearch(map, { //智能搜索 onSearchComplete: myFun }); local.search(myValue); } </script>

 vue 版本

<template>
  <div>
    <bg-popout
      :isShow.sync="addEquimentShowTree"
      class="addEquiment"
      width="50"
      height="65"
      style="position: fixed;left: 0;top: 0;bottom: 0;right: 0;margin: auto;"
    >
      <div class="centerbox treeList">
        <div class="title">选择区域位置</div>
        <div class="center">
          <div id="location" class="location" ref="location"></div>
          <div id="r-result" class="r-result">
            搜索地址 :
            <input type="text" id="suggestId" class="suggestId" placeholder="请输入" />
          </div>
          <div
            id="searchResultPanel"
            style="border:1px solid #C0C0C0;150px;height:auto; display:none;"
          ></div>
        </div>
        <div class="footer">
          经度:
          <el-input v-model="lng" class="inputstyle" placeholder="请输入经度"></el-input>纬度:
          <el-input v-model="lat" class="inputstyle" placeholder="请输入纬度"></el-input>

          <el-button type="success" class="btn" @click="ensure" size="small">确定</el-button>
          <el-button type="warning" class="btn" @click="cancel" size="small">取消</el-button>
          <el-button type="primary" class="btn" @click="setting" size="small">设置坐标</el-button>
        </div>
      </div>
    </bg-popout>
  </div>
</template>
<script>
import bgPopout from "@/components/bgPopout.vue";
import { dvgetMapCenter } from "@/api/mapControls.js";

export default {
  name: "addEquimentvs",
  components: {
    bgPopout
  },
  computed: {},
  data() {
    return {
      addEquimentShowTree: false,
      id: 0,
      props: {
        label: "name",
        children: "children",
        isLeaf: "leaf"
      },
      tree: [],
      checkedId: "",
      areaTree: {},
      lat: null,
      lng: null,
      map: null,
      marker: null,
      type: "", //判断是编辑的还是新增
      myValue: ""
    };
  },
  watch: {
    addEquimentShowTree(val) {
      if (!val) {
        this.map.removeEventListener("click", this.MapClick);
        this.map = null;
      }
    }
  },
  created() {},
  mounted() {
    //this.initMap()
  },
  methods: {
    show(type, lng, lat) {
      this.addEquimentShowTree = true;
      //11是編輯
      this.type = type;
      //   console.log(type);
      if (type == 11) {
        this.lng = lng;
        this.lat = lat;
        if (lng == null || lng == "0") {
          this.dvgetMapCenter_();
        } else {
          setTimeout(() => {
            this.initMap();
          }, 30);
        }
      } else {
        this.dvgetMapCenter_();
      }
    },
    ensure() {
      this.addEquimentShowTree = false;
      this.$emit("locationcallback", this.lng, this.lat);
    },
    //取消
    cancel() {
      this.addEquimentShowTree = false;
    },
    // 设置
    setting() {
      this.addMapClick();
    },
    //获取中心点
    dvgetMapCenter_() {
      dvgetMapCenter().then(res => {
        if (res.code == 200) {
          let data = res.body || {};
          this.lng = data.lng;
          this.lat = data.lat;
          this.initMap();
        }
      });
    },
    //绘制地图
    initMap() {
      this.map = new BMap.Map("location");
      let point = new BMap.Point(this.lng, this.lat);
      this.map.centerAndZoom(point, 15);
      this.map.enableScrollWheelZoom(true);
      this.marker = new BMap.Marker(point); // 创建标注
      this.map.addOverlay(this.marker);
      //类型切换 20200408
      this.map.addControl(
        new BMap.MapTypeControl({
          mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
          anchor: BMAP_ANCHOR_TOP_LEFT
        })
      );
      //以下是搜索功能

      //建立一个自动完成的对象
      let ac = new BMap.Autocomplete({
        input: "suggestId",
        location: this.map
      });
      //鼠标放在下拉列表上的事件
      ac.addEventListener("onhighlight", e => {
        let str = "";
        let _value = e.fromitem.value;
        let value = "";
        if (e.fromitem.index > -1) {
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business;
        }
        str =
          "FromItem<br />index = " +
          e.fromitem.index +
          "<br />value = " +
          value;
        value = "";
        if (e.toitem.index > -1) {
          _value = e.toitem.value;
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business;
        }
        str +=
          "<br />ToItem<br />index = " +
          e.toitem.index +
          "<br />value = " +
          value;
        this.GOing("searchResultPanel").innerHTML = str;
      });
      //鼠标点击下拉列表后的事件
      ac.addEventListener("onconfirm", e => {
        let _value = e.item.value;
        this.myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business;
        this.GOing("searchResultPanel").innerHTML =
          "onconfirm<br />index = " +
          e.item.index +
          "<br />this.myValue = " +
          this.myValue;
        this.setPlace();
      });
    },
    //获取id的值
    GOing(id) {
      return document.getElementById(id);
    },
    setPlace() {
      this.map.clearOverlays(); //清除地图上所有覆盖物
      let that = this;
      function myFun() {
        //获取第一个智能搜索的结果
        let pp = local.getResults().getPoi(0).point;
        that.map.centerAndZoom(pp, 18);
        //添加标注
        that.map.addOverlay(new BMap.Marker(pp));
      }
      //智能搜索
      let local = new BMap.LocalSearch(this.map, {
        onSearchComplete: myFun
      });
      local.search(this.myValue);
    },
    //启动标点  监听事件
    addMapClick() {
      this.map.addEventListener("click", this.MapClick);
    },
    MapClick(e) {
      if (this.marker) {
        this.map.clearOverlays();
      }
      this.lng = e.point.lng;
      this.lat = e.point.lat;
      let point = new BMap.Point(this.lng, this.lat);
      this.marker = new BMap.Marker(point); // 创建标注
      this.map.panTo(point);
      this.map.addOverlay(this.marker);
    }
  }
};
</script>
<style lang="less" scoped>
.addEquiment {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 30px 0;
}

.customized_input {
  width: 180px !important;
}

.centerbox {
  width: 100%;
  box-sizing: border-box;
  padding: 0px 20px 0 20px;
}

.centerbox .el-dialog {
  -webkit-backface-visibility: hidden !important;
}

.centerbox .title {
  font-size: 20px;
  color: #01c1da;
  width: 100%;
  height: 50px;
}

.filter-tree {
  width: 100%;
  background: rgba(0, 0, 0, 0);
  color: #ffffff;
}

.center {
  width: 100%;
  height: 40.5vh;
  position: relative;

  .location {
    width: 100%;
    height: 100%;
  }
}

.footer {
  width: 100%;
  font-size: 16px;
  margin-top: 15px;

  .btn {
    float: right;
    margin-left: 10px;
  }

  .inputstyle {
    width: 180px;
  }
}

.center .r-result {
  display: inline-block;
  position: absolute;
  right: 5px;
  top: 5px;
  color: #000;
  font-size: 16px;
  z-index: 999999;
}

.center .r-result .suggestId {
  border: 1px solid #73859f;
  outline: none;
  width: 220px;
  height: 30px;
  border-radius: 4px;
  padding-left: 5px;
  z-index: 999999;
}
.center .r-result .tangram-suggestion-main {
  z-index: 9999 !important;
}
</style>
原文地址:https://www.cnblogs.com/Byme/p/10118577.html