vue中調用百度地圖獲取經緯度的實現

項目中,需要實現獲取當前位置的經緯度,或者搜索某個位置並獲取經緯度信息,我使用的的是vue,地圖使用的是百度地圖。

vue調用百度地圖,獲取當前經緯度,js獲取當前經緯度

默認自動獲取當前位置經緯度

js獲取經緯度

拖動小紅標 獲取經緯度

js獲取經緯度 js獲取當前經緯度

關鍵詞 查詢獲取經緯度

前期準備

首先,我們需要取百度官方申請一個地圖api秘鑰,https://lbsyun.baidu.com/apiconsole/key 進入後在應用管理,我的應用去申請即可。

申請好以後,我們打開vue項目中public文件下的index.html文件,拼接百度AK值並引入

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=WFKACU6v7aiUdnkgtMCqdWBZC68KpUXv"></script>  

如上所示,紅色區域為AK值,自行拼接自己的,可以設置權限為公開或者針對網址白名單。

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=WFKACU6v7aiUdnkgtMCqdWBZC68KpUXv"></script>

我使用瞭elementui的彈窗,輸入框,提示,如果你沒使用elementui,記得更換哦!

HTML代碼

<template>
  <div>
    <el-dialog
      @close="clearDialog"
      :close-on-click-modal="false"
      :title="text"
      style="text-align: left"
      :visible.sync="popup"
      width="30%"
    >
      <div class="form-layer">
        <el-form label-width="100px" size="mini">
          <el-form-item label="獲取定位">
            <el-button type="primary" @click="fixedPos">重新定位</el-button>
          </el-form-item>
          <el-form-item label="當前緯度">
            <p>{{latitude}}</p>
          </el-form-item>
          <el-form-item label="當前經度">
            <p>{{longitude}}</p>
          </el-form-item>
          <el-form-item>
            <div class="f-a-c">
              <el-input v-model="keyWords" placeholder="請輸入地區" style="width: 230px;margin-right: 6px;"></el-input>
              <el-button type="primary" @click="setPlace" :disabled="!keyWords">查詢</el-button>
            </div>
          </el-form-item>
        </el-form>
        <div id="map"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          v-if="type != '2'"
          @click="btnSubmit()"
          >確 認</el-button
        >
        <el-button size="small" @click="popup = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

JS代碼

<script>
  export default {
    name: "mapView",
    data() {
      return {
        map: null,
        local: null,
        mk: null,
        latitude: '',
        longitude: '',
        keyWords: ''
      };
    },
    methods: {
      // 打開彈窗,name為彈窗名稱
      async openDialog(name) {
        this.text = name;
        this.popup = true;
        this.initMap();
      },
      // 確認
      btnSubmit() {
        let key = {
          latitude: this.latitude,
          longitude: this.longitude
        }
        // 打印經緯度
        console.log(key);
        this.popup = false;
      },
      initMap() {
        this.$nextTick(() => {
          this.map = new BMap.Map("map");
          let point = new BMap.Point(116.404, 39.915);
          this.map.centerAndZoom(point, 12);
          this.map.enableScrollWheelZoom(true); // 開啟鼠標滾輪縮放
          this.map.addControl(new BMap.NavigationControl());
          this.fixedPos();
        });
      },
      // 點擊定位-定位到當前位置
      fixedPos() {
        const _this = this;
        const geolocation = new BMap.Geolocation();
        this.confirmLoading = true;
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            _this.handleMarker(_this, r.point);
            let myGeo = new BMap.Geocoder();
            myGeo.getLocation(
              new BMap.Point(r.point.lng, r.point.lat),
              function (result) {
                _this.confirmLoading = false;
                if (result) {
                  _this.latitude = result.point.lat;
                  _this.longitude = result.point.lng;
                }
              }
            );
          } else {
            _this.$message.error("failed" + this.getStatus());
          }
        });
      },
      // 搜索地址
      setPlace() {
        this.local = new BMap.LocalSearch(this.map, {
          onSearchComplete: this.searchPlace,
        });
        this.local.search(this.keyWords);
      },
      searchPlace() {
        if (this.local.getResults() != undefined) {
          this.map.clearOverlays(); //清除地圖上所有覆蓋物
          if (this.local.getResults().getPoi(0)) {
            let point = this.local.getResults().getPoi(0).point; //獲取第一個智能搜索的結果
            this.map.centerAndZoom(point, 18);
            this.handleMarker(this, point);
            console.log("經度:" + point.lng + "--" + "緯度" + point.lat);
            this.latitude = point.lat;
            this.longitude = point.lng;
          } else {
            this.$message.error("未匹配到地點!");
          }
        } else {
          this.$message.error("未找到搜索結果!");
        }
      },
      // 設置標註
      handleMarker(obj, point) {
        let that = this;
        obj.mk = new BMap.Marker(point);
        obj.map.addOverlay(obj.mk);
        obj.mk.enableDragging(); // 可拖拽
        obj.mk.addEventListener("dragend", function (e) {
          // 監聽標註的拖拽,獲取拖拽後的經緯度
          that.latitude = e.point.lat;
          that.longitude = e.point.lng;
        });
        obj.map.panTo(point);
      },
    }
  };
</script>

CSS代碼

<style scoped>
  .form-layer {
    width: 100%;
  }
  #map {
    margin-top: 30px;
    width: 100%;
    height: 300px;
    border: 1px solid gray;
    box-sizing: border-box;
    overflow: hidden;
  }
  /deep/ .el-dialog {
    min-width: 550px;
  }
  /deep/ .el-dialog__body {
    padding: 10px;
  }
</style>

完整代碼

<template>
  <div>
    <el-dialog
      @close="clearDialog"
      :close-on-click-modal="false"
      :title="text"
      style="text-align: left"
      :visible.sync="popup"
      width="30%"
    >
      <div class="form-layer">
        <el-form label-width="100px" size="mini">
          <el-form-item label="獲取定位">
            <el-button type="primary" @click="fixedPos">重新定位</el-button>
          </el-form-item>
          <el-form-item label="當前緯度">
            <p>{{latitude}}</p>
          </el-form-item>
          <el-form-item label="當前經度">
            <p>{{longitude}}</p>
          </el-form-item>
          <el-form-item>
            <div class="f-a-c">
              <el-input v-model="keyWords" placeholder="請輸入地區" style="width: 230px;margin-right: 6px;"></el-input>
              <el-button type="primary" @click="setPlace" :disabled="!keyWords">查詢</el-button>
            </div>
          </el-form-item>
        </el-form>
        <div id="map"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          v-if="type != '2'"
          @click="btnSubmit()"
          >確 認</el-button
        >
        <el-button size="small" @click="popup = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: "mapView",
    data() {
      return {
        map: null,
        local: null,
        mk: null,
        latitude: '',
        longitude: '',
        keyWords: ''
      };
    },
    methods: {
      // 打開彈窗,name為彈窗名稱
      async openDialog(name) {
        this.text = name;
        this.popup = true;
        this.initMap();
      },
      // 確認
      btnSubmit() {
        let key = {
          latitude: this.latitude,
          longitude: this.longitude
        }
        // 打印經緯度
        console.log(key);
        this.popup = false;
      },
      initMap() {
        this.$nextTick(() => {
          this.map = new BMap.Map("map");
          let point = new BMap.Point(116.404, 39.915);
          this.map.centerAndZoom(point, 12);
          this.map.enableScrollWheelZoom(true); // 開啟鼠標滾輪縮放
          this.map.addControl(new BMap.NavigationControl());
          this.fixedPos();
        });
      },
      // 點擊定位-定位到當前位置
      fixedPos() {
        const _this = this;
        const geolocation = new BMap.Geolocation();
        this.confirmLoading = true;
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            _this.handleMarker(_this, r.point);
            let myGeo = new BMap.Geocoder();
            myGeo.getLocation(
              new BMap.Point(r.point.lng, r.point.lat),
              function (result) {
                _this.confirmLoading = false;
                if (result) {
                  _this.latitude = result.point.lat;
                  _this.longitude = result.point.lng;
                }
              }
            );
          } else {
            _this.$message.error("failed" + this.getStatus());
          }
        });
      },
      // 搜索地址
      setPlace() {
        this.local = new BMap.LocalSearch(this.map, {
          onSearchComplete: this.searchPlace,
        });
        this.local.search(this.keyWords);
      },
      searchPlace() {
        if (this.local.getResults() != undefined) {
          this.map.clearOverlays(); //清除地圖上所有覆蓋物
          if (this.local.getResults().getPoi(0)) {
            let point = this.local.getResults().getPoi(0).point; //獲取第一個智能搜索的結果
            this.map.centerAndZoom(point, 18);
            this.handleMarker(this, point);
            console.log("經度:" + point.lng + "--" + "緯度" + point.lat);
            this.latitude = point.lat;
            this.longitude = point.lng;
          } else {
            this.$message.error("未匹配到地點!");
          }
        } else {
          this.$message.error("未找到搜索結果!");
        }
      },
      // 設置標註
      handleMarker(obj, point) {
        let that = this;
        obj.mk = new BMap.Marker(point);
        obj.map.addOverlay(obj.mk);
        obj.mk.enableDragging(); // 可拖拽
        obj.mk.addEventListener("dragend", function (e) {
          // 監聽標註的拖拽,獲取拖拽後的經緯度
          that.latitude = e.point.lat;
          that.longitude = e.point.lng;
        });
        obj.map.panTo(point);
      },
    }
  };
</script>
<style scoped>
  .form-layer {
    width: 100%;
  }
  #map {
    margin-top: 30px;
    width: 100%;
    height: 300px;
    border: 1px solid gray;
    box-sizing: border-box;
    overflow: hidden;
  }
  /deep/ .el-dialog {
    min-width: 550px;
  }
  /deep/ .el-dialog__body {
    padding: 10px;
  }
</style>

到此這篇關於vue中調用百度地圖獲取經緯度的實現的文章就介紹到這瞭,更多相關vue調用百度地圖獲取經緯度內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: