vue2使用高德地图实现搜索定位和点击获取经纬度和地址

一、下载高德地图的依赖

npm i @amap/amap-jsapi-loader -S

二、登录高德开放平台获取key和安全密钥

2.1进入高德地图注册账号密码

高德开放平台

2.2获取key值和安全密钥

控制台>应用管理>我的应用>创建新应用>添加key值>服务平台选择:Web端(JS API)>获取key值和安全密钥

三、项目引入高德地图并且实现搜索定位和点击获取经纬度

代码部分

<template>
  <el-dialog :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" :close-on-click-modal="false" :visible.sync="visible"
    class="rv-dialog rv-dialog_center" lock-scroll width="74%">
    <el-row :gutter="15" class="">
      <el-col :span="8">
        <el-form ref="elForm" :model="dataForm" :rules="rules" size="small" label-width="70px" label-position="right"
          :disabled="!!isDetail">
          <el-col :span="24">
            <el-form-item label="名称" prop="kqName">
              <el-input v-model="dataForm.kqName" placeholder="请输入" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="地点" prop="kqLocation">
              <el-input v-model="dataForm.kqLocation" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="经度" prop="kqLongitude">
              <el-input v-model="dataForm.kqLongitude" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="纬度" prop="kqLatitude">
              <el-input v-model="dataForm.kqLatitude" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="单位" prop="kqWorkUnit">
              <el-input v-model="dataForm.kqWorkUnit" placeholder="请输入" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="授权" prop="cronkqAccredit">
              <uDSelect v-model="dataForm.cronkqAccredit" :multiple="true" placeholder="选择范围" title="选择范围" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="有效签卡范围(米)" label-width="150px" prop="kqValidCardRange">
              <el-input v-model="dataForm.kqValidCardRange" placeholder="请输入" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-col>
      <el-col :span="16">
        <div style="width: 100%">
          <div class="search_box">
            <div class="label">关键字搜索</div>
            <el-input v-model="input" placeholder="请输入内容" id="tipinput"></el-input>
          </div>
          <div ref="gaode_Map" id="gaode_Map"></div>
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader"; //引入AMapLoader
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "申请的安全密钥",
};
export default {
  components: {},
  props: [],
  data () {
    return {
      loading: false,
      visible: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      rules: {},
      input: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
    };
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    // 地图初始化
    initMap () {
      let centerLen = [116.397428, 39.90923];
      AMapLoader.load({
        key: "申请的key值", // 申请好的Web端开发者Key,首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("gaode_Map", {
            // 设置地图容器id
            viewMode: "3D", //  是否为3D地图模式
            zoom: 18, // 初始化地图级别
            center: centerLen, //中心点坐标
            resizeEnable: true,
          });
          this.setMarker(centerLen)
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => { });
    },
    // 关键字查询
    searchMap () {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },
    //选中查询出的记录
    selectSite (e) {
      if (e.poi.location) {
        // this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        let geocoder = new AMap.Geocoder({});
        let that = this;
        geocoder.getAddress(this.lnglat, function (status, result) {
          if (status === "complete" && result.regeocode) {
            that.province = result.regeocode.addressComponent.province;
            that.city = result.regeocode.addressComponent.city;
            //自己想要赋的值,根据自己的做修改
            that.$set(that.form, "province", that.province);
            that.$set(that.form, "city", that.city);
            that.$set(that.form, "address", e.poi.name);
            that.$set(
              that.form,
              "coordinate",
              e.poi.location.lng + "," + e.poi.location.lat
            ); //纬度,经度
          } else {
          }
        });
      } else {
        this.$message.error("查询地址失败,请重新输入地址");
      }
    },
    // 点击地图事件获取经纬度,并添加标记
    clickMapHandler (e) {
      this.dataForm.kqLongitude = e.lnglat.getLng();
      this.dataForm.kqLatitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      // 点击地图上的位置,根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          that.dataForm.kqLocation = result.regeocode.formattedAddress;
        } else {
        }
      });
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
      };
      this.input = that.address; //把查询到的地址赋值到输入框
    },
    //  添加标记
    setMarker (lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // 删除之前后的标记点
    removeMarker () {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },
  },
};
</script>


<style lang="scss">
.search_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;

  .label {
    color: #000;
    width: 100px;
  }
}

.content {
  position: relative;
}

#panel {
  position: absolute;
  top: 50px;
  right: 20px;
}

#gaode_Map {
  overflow: hidden;
  width: 100%;
  height: 540px;
  margin: 0;
}

.amap-sug-result {
  z-index: 2999 !important;
}
</style>

最终实现的效果图

  • 9
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
### 回答1: 在Vue中引入高德地图并根据输入内容实现定位获取经纬度地址,可以按照以下步骤进行: 1. 首先,需要在项目中引入高德地图的JS API。可以通过在index.html文件中引入高德地图的JS文件来实现,例如在head标签内添加以下代码: ```html <script src="https://webapi.amap.com/maps?v=1.4.15"></script> ``` 2. 在Vue组件中,可以通过在mounted钩子函数中初始化地图对象,如下所示: ```javascript mounted() { this.initMap(); }, methods: { initMap() { // 创建地图对象 const map = new AMap.Map("mapContainer", { zoom: 14 // 设置地图的缩放级别 }); // 使用Autocomplete组件实现输入提示 const autoComplete = new AMap.Autocomplete({ input: "inputContainer" // 设置输入提示的输入框 }); // 输入提示选中事件监听 AMap.event.addListener(autoComplete, "select", e => { // 获取选中的结果 const location = e.poi.location; // 获取经纬度 const address = e.poi.district + e.poi.address; // 获取地址 console.log("经纬度:", location); console.log("地址:", address); }); } } ``` 上述代码中,首先在mounted钩子函数中初始化了地图对象,并设置了地图的缩放级别。然后使用Autocomplete组件来实现输入提示,将输入提示关联到输入框(id为inputContainer)。接着,监听Autocomplete组件的select事件,在事件处理函数中获取选中的结果,包括经纬度地址。 3. 在Vue模板中,需要添加包含地图和输入框的元素,如下所示: ```html <template> <div> <input id="inputContainer" type="text" placeholder="请输入地址" /> <div id="mapContainer"></div> </div> </template> ``` 上述代码中,输入框使用id为inputContainer,并在初始化地图对象中将其设置给Autocomplete组件,地图容器使用id为mapContainer。 通过以上步骤,在Vue中可以引入高德地图实现根据输入的定位,并获取对应的经纬度地址。 ### 回答2: 在Vue中引入高德地图定位获取经纬度地址需要以下步骤: 1. 在项目中安装高德地图JavaScript API库,可以使用npm安装:npm install @amap/amap-jsapi-loader。 2. 在Vue组件中引入amap-jsapi-loader库。在需要显示地图的组件中,可以使用以下代码进行引入: ```javascript import AMapLoader from '@amap/amap-jsapi-loader'; export default { data() { return { mapInstance: null, location: null, address: null, } }, mounted() { this.loadMap(); }, methods: { loadMap() { AMapLoader.load({ key: 'YOUR_AMAP_KEY', version: '2.0', // 高德地图API的版本号 plugins: ['AMap.Geolocation'], }).then((AMap) => { this.mapInstance = new AMap.Map('mapContainer'); this.addGeolocationControl(); }).catch((error) => { console.log('地图加载失败:', error); }); }, addGeolocationControl() { this.mapInstance.plugin('AMap.Geolocation', () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, timeout: 10000, buttonOffset: new AMap.Pixel(10, 10), }); geolocation.getCurrentPosition((status, result) => { if (status === 'complete') { this.location = result.position; //获取经纬度 this.address = result.formattedAddress; //获取地址 } }); this.mapInstance.addControl(geolocation); }); }, }, } ``` 3. 在组件的template中添加一个包含地图的div元素,并绑定id为'mapContainer': ```html <template> <div> <div id="mapContainer"></div> <div>经度:{{location.lng}}</div> <div>纬度:{{location.lat}}</div> <div>地址:{{address}}</div> </div> </template> ``` 4. 在Vue组件中的data属性中定义location和address两个变量,用于存储定位经纬度地址。 5. 在组件的mounted生命周期钩子中调用loadMap方法,该方法会加载地图和Geolocation插件,并创建地图实例。 6. 在addGeolocationControl方法中创建Geolocation实例,并通过getCurrentPosition方法获取当前位置的经纬度地址定位成功后,将结果存储在组件的data属性中。 7. 在template中使用插值表达式显示定位结果。 注意:在代码中的'YOUR_AMAP_KEY'需要替换为你在高德地图开发者平台申请的API Key。同时,请根据实际情况进行适当的样式和错误处理。 ### 回答3: 要实现Vue中引入高德地图,并根据用户输入定位获取经纬度地址,可以按照以下步骤进行操作: 1. 在Vue项目使用npm安装高德地图SDK: ``` npm install vue-amap --save ``` 2. 在Vue的main.js文件中引入高德地图模块,并进行配置: ```javascript import VueAMap from 'vue-amap'; Vue.use(VueAMap); VueAMap.initAMapApiLoader({ key: 'your-amap-api-key', plugin: ['Geocoder'], }); ``` - 'your-amap-api-key'是你在高德地图开放平台上申请的API Key。 3. 创建一个组件,用于输入位置信息和显示地图: ```vue <template> <div> <input v-model="address" placeholder="请输入位置信息" /> <button @click="getLocation">获取经纬度地址</button> <div>{{latitude}}, {{longitude}}</div> <div>{{formattedAddress}}</div> <div id="mapContainer"></div> </div> </template> <script> export default { data() { return { address: '', latitude: '', longitude: '', formattedAddress: '', }; }, methods: { getLocation() { const geocoder = new AMap.Geocoder(); geocoder.getLocation(this.address, (status, result) => { if (status === 'complete' && result.info === 'OK') { this.latitude = result.geocodes[0].location.lat; this.longitude = result.geocodes[0].location.lng; this.formattedAddress = result.geocodes[0].formattedAddress; this.showMap(); } }); }, showMap() { // 使用AMap.Map来展示地图,根据this.latitude和this.longitude进行定位 }, }, mounted() { this.$nextTick(() => { // 根据DOM元素id('mapContainer')来展示地图 }); }, }; </script> ``` 以上代码中,我们通过`v-model`指令绑定input的值到Vue实例的`address`属性。当点击获取经纬度地址”的按钮时,调用`getLocation`方法获取经纬度地址,并展示在页面上。接着,我们可以使用`AMap.Map`来展示地图,根据`this.latitude`和`this.longitude`来定位地图。这里只提供一个简单的演示,具体地图展示的功能根据项目需求进行更详细的配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值