vue中调用百度地图获取经纬度的实现

2022-04-15 0 1,030

项目中,需要实现获取当前位置的经纬度,或者搜索某个位置并获取经纬度信息,我使用的的是vue,地图使用的是百度地图。

vue中调用百度地图获取经纬度的实现

默认自动获取当前位置经纬度

vue中调用百度地图获取经纬度的实现

拖动小红标 获取经纬度

vue中调用百度地图获取经纬度的实现

关键词 查询获取经纬度

前期准备

首先,我们需要取百度官方申请一个地图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调用百度地图获取经纬度内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript vue中调用百度地图获取经纬度的实现 https://www.niceym.com/22584.html