vue2高德地图选点

文章描述了一个使用Vue.js和AMapJavaScriptAPI构建的地理位置表单组件,包括地址、经度和纬度的输入,以及地图搜索和定位功能。用户可以通过关键字搜索地点,并在地图上显示标记。
摘要由CSDN通过智能技术生成
<template>
  <el-dialog :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" :close-on-click-modal="false" :visible.sync="show" class="rv-dialog rv-dialog_center" lock-scroll width="74%" :before-close="closeForm">
    <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="address">
              <el-input v-model="dataForm.address" 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-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="closeForm">取 消</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: {
    show: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      isDetail: false,
      dataForm: {
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        address: ''
      },
      rules: {},
      input: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
      citysearch: null,
      geoLoc: null,
      cityCode: ''
    };
  },
  computed: {},
  watch: {
    show(val) {
      if (val) {
        this.initMap();
      }
    },
  },
  created() { },
  mounted() {
  },
  methods: {
    // 地图初始化
    initMap() {
      let centerLen = [120.264777, 30.221391];
      AMapLoader.load({
        key: "***", // 申请好的Web端开发者Key,首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder", "AMap.Geolocation", "AMap.CitySearch"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("gaode_Map", {
            // 设置地图容器id
            viewMode: "3D", //  是否为3D地图模式
            zoom: 18, // 初始化地图级别
            center: centerLen, //中心点坐标
            resizeEnable: true,
          });
          // 浏览器城市定位
          this.getCityLocation()
          // 设置中心点
          this.setMarker(centerLen);
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);

        })
        .catch((e) => { });
    },
    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        city: this.cityCode,
        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.$set(this.dataForm, "kqLongitude", e.poi.location.lng);
        this.$set(this.dataForm, "kqLatitude", e.poi.location.lat);
        this.$set(
          this.dataForm,
          "kqLocation",
          e.poi.location.lng + "," + e.poi.location.lat
        ); //纬度,经度
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        this.placeSearch.on('markerClick', this.markerClick)
        let geocoder = new AMap.Geocoder({});
        geocoder.getAddress(this.lnglat, (status, result) => {
          if (status === "complete" && result.regeocode) {
            this.regeoAddress(result)
          }
        });
      } 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, (status, result) => {
        if (status === "complete" && result.regeocode) {
          this.regeoAddress(result)
        }
      });
      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);
      }
    },
    closeForm() {
      this.$emit("update:show", false);
    },
    dataFormSubmit() {
      this.$emit("handlerLocation", this.dataForm);
      this.closeForm();
    },
    regeoAddress(result) {
      let {
        formattedAddress,
        addressComponent: {
          township,
        },
      } = result.regeocode
      let indexStr = formattedAddress.indexOf(township) + township.length;
      let address = formattedAddress;
      if (indexStr != -1) {
        address = address.substring(indexStr);
      }
      this.$set(this.dataForm, "address", address);
    },
    // 点击搜索出来的poi点标记
    markerClick(e) {
      this.dataForm.address = e.data.name;
      this.dataForm.kqLatitude = e.data.location.lat;
      this.dataForm.kqLongitude = e.data.location.lng;
    },
    getCityLocation() {
      this.citysearch = new AMap.CitySearch();
      this.citysearch.getLocalCity((status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          if (result && result.city && result.bounds) {
            this.cityCode = result.adcode
            // 关键字查询
            this.searchMap();
          }
        }
      });
    }
  },
};
</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>

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,以下是一个简单的 Vue 接入高德地图选点的示例: 1. 在 index.html 中引入高德地图的 js 文件 ``` <script src="//webapi.amap.com/maps?v=1.4.10&key=your-amap-key"></script> ``` 2. 在 App.vue 中创建地图容器和初始化地图 ``` <template> <div id="map-container"></div> </template> <script> export default { mounted() { // 创建地图容器 const map = new AMap.Map("map-container", { zoom: 10 }); // 初始化地图 AMap.plugin("AMap.Geolocation", () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, // 是否使用高精度定位,默认:true timeout: 10000, // 超过10秒后停止定位,默认:5s buttonPosition: "RB", // 定位按钮的停靠位置 zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点 }); map.addControl(geolocation); geolocation.getCurrentPosition(); }); } }; </script> ``` 3. 添加选点功能 ``` <template> <div> <div id="map-container"></div> <div> <button @click="choosePoint">选点</button> <span>经度: {{ location.lng }}</span> <span>纬度: {{ location.lat }}</span> </div> </div> </template> <script> export default { data() { return { location: {} // 保存选定的经纬度 }; }, mounted() { const map = new AMap.Map("map-container", { zoom: 10 }); AMap.plugin("AMap.Geolocation", () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, timeout: 10000, buttonPosition: "RB", zoomToAccuracy: true }); map.addControl(geolocation); geolocation.getCurrentPosition(); }); }, methods: { choosePoint() { // 定义选点插件 const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, timeout: 10000, buttonPosition: "RB", zoomToAccuracy: true }); // 打开选点插件 map.addControl(geolocation); geolocation.getCurrentPosition(); // 监听选点事件 AMap.event.addListener(geolocation, "complete", result => { this.location.lng = result.position.lng; this.location.lat = result.position.lat; }); } } }; </script> ``` 希望这个示例对你有所帮助!
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值