web端使用高德地图

一、申请高德key和秘钥

二、在项目中引入所需功能js、css文件

<script src="https://webapi.amap.com/maps?v=2.0&key=XXXXXXXXXXXXX"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<script
  type="text/javascript"
  src="https://webapi.amap.com/demos/js/liteToolbar.js"
></script>
   

三、实现地图选点、回显选点

<template>
  <el-dialog title="选择地址" :visible.sync="MapVisible" width="960px">
    <el-form
      ref="Addressform"
      :model="Addressform"
      :rules="Addressrules"
      label-width="65px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="省" prop="province">
            <el-select
              v-model="Addressform.provinceId"
              placeholder=""
              filterable
              style="width: 100%"
              @change="changeProvince"
            >
              <el-option
                v-for="dict in provinceOptions"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="市" prop="city">
            <el-select
              v-model="Addressform.cityId"
              filterable
              placeholder=""
              style="width: 100%"
              @change="changeCity"
            >
              <el-option
                v-for="dict in cityOptions"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="区" prop="region">
            <el-select
              v-model="Addressform.regionId"
              placeholder=""
              filterable
              style="width: 100%"
              @change="changeRegion"
            >
              <el-option
                v-for="dict in regionOptions"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="乡(镇)" prop="street">
            <el-select
              v-model="Addressform.streetId"
              placeholder=""
              filterable
              style="width: 100%"
              @change="changeStreet"
            >
              <el-option
                v-for="dict in streetOptions"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row style="display: flex; align-items: end">
        <el-col :span="20">
          <el-form-item label="村" prop="village">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入村"
              v-model="Addressform.village"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="searchAddress"
              :disabled="!Addressform.streetId"
              >搜索</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div id="mapselectpoint-container"></div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="MapVisible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="submitAddress"
        :disabled="!point || !Addressform.streetId"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import axios from "axios";
import {
  selectAreaByParentCode,
  addFarmerAddress,
  getFarmerAddressInfo,
  updateFarmerAddressInfo,
} from "@/api/business/farmerInfo";
export default {
  name: "homepage",
  props: {
    farmerId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      MapVisible: false,
      icon: {
        // 图标类型,现阶段只支持 image 类型
        type: "image",
        // 图片 url
        image:
          "https://a.amap.com/jsapi_demos/static/demo-center/marker/express2.png",
        // 图片尺寸
        size: [64, 30],
        // 图片相对 position 的锚点,默认为 bottom-center
        anchor: "center",
      },
      textStyle: {
        fontSize: 12,
        fontWeight: "normal",
        fillColor: "#22886f",
        strokeColor: "#fff",
        strokeWidth: 2,
        fold: true,
        padding: "2, 5",
      },
      map: null,
      marker: null,
      // 表单信息
      Addressform: {
        provinceId: undefined,
        province: undefined,
        city: undefined,
        cityId: undefined,
        region: undefined,
        regionId: undefined,
        street: undefined,
        streetId: undefined,
        village: undefined,
      },
      Addressrules: {
        province: [
          {
            required: true,
            message: "省不能为空",
            trigger: "change",
          },
        ],
        city: [
          {
            required: true,
            message: "市不能为空",
            trigger: "change",
          },
        ],
        region: [
          {
            required: true,
            message: "区不能为空",
            trigger: "change",
          },
        ],
        street: [
          {
            required: true,
            message: "镇不能为空",
            trigger: "change",
          },
        ],
        village: [
          {
            required: true,
            message: "村不能为空",
            trigger: "blur",
          },
        ],
      },
      provinceOptions: [],
      cityOptions: [],
      regionOptions: [],
      streetOptions: [],
      //   图上点位
      point: null,
    };
  },

  mounted() {},
  methods: {
    initMap(id) {
      // 新增点位
      this.MapVisible = true;
      this.$nextTick(async function () {
        // 重置信息
        this.reset();
        // 获取省级下拉内容
        if (!id) {
          // 如果是新增
          let res = await selectAreaByParentCode({ parentId: 1 });
          this.provinceOptions = res.data;
        }
        // 地图初始化
        this.map = new AMap.Map("mapselectpoint-container", {
          zoom: 15.8,
          //   center: [116.469881, 39.993599], //不设置自动定位到当前所在城市
        });
        this.map.setMapStyle("amap://styles/xxxxxxxxxxxxxxxxxxxx"); //设置地图的显示样式
        // 给地图绑定一个点击事件
        this.map.on("click", this.showInfoClick); //地图点击事件
        if (id) {
          // 如果是修改
          //   回显地址
          // 地址详情查询+回显
          getFarmerAddressInfo(id).then((res) => {
            this.Addressform = res.data;

            // 获取省市区镇下拉数据
            selectAreaByParentCode({ parentId: 1 }).then((res) => {
              // 省
              this.provinceOptions = res.data;
            });
            selectAreaByParentCode({
              parentId: this.Addressform.provinceId,
            }).then((res) => {
              // 市
              this.cityOptions = res.data;
            });
            selectAreaByParentCode({ parentId: this.Addressform.cityId }).then(
              (res) => {
                // 区
                this.regionOptions = res.data;
              }
            );
            selectAreaByParentCode({
              parentId: this.Addressform.regionId,
            }).then((res) => {
              // 镇
              this.streetOptions = res.data;
            });
            // 地址回显之后,给地图打点
            this.setPoint([
              this.Addressform.longitude,
              this.Addressform.latitude,
            ]);
            this.map.setZoomAndCenter(18, [
              this.Addressform.longitude,
              this.Addressform.latitude,
            ]);
          });
        }
      });
    },
    reset() {
      this.point = null;
      this.cityOptions = [];
      this.regionOptions = [];
      this.streetOptions = [];
      this.Addressform = {
        provinceId: undefined,
        province: undefined,
        city: undefined,
        cityId: undefined,
        region: undefined,
        regionId: undefined,
        street: undefined,
        streetId: undefined,
        village: undefined,
      };
      this.resetForm("Addressform");
    },
    setPoint(point) {
      //    保存点位,如果点位存在则可以提交地址
      this.point = point;
      // 添加一个点位
      if (this.marker) {
        this.map.remove(this.marker);
      }
      this.marker = new AMap.Marker({
        icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: point,
        offset: new AMap.Pixel(-13, -30),
      });
      this.marker.setMap(this.map);
    },
    showInfoClick(e) {
      // 点击地图,在地图上打个标记
      this.setPoint([e.lnglat.getLng(), e.lnglat.getLat()]);

      // 通过点位获取省市区信息并回显
      this.regeoCode([e.lnglat.getLng(), e.lnglat.getLat()]);
    },
    async regeoCode(point) {
      // 获取标记位置信息:省市区镇用于保存信息
      let res = await axios(
        `https://restapi.amap.com/v3/geocode/regeo?location=${point.join(
          ","
        )}&key=f4d2e724f0ba6fe3b1cb5f841bce7a5e`
      );

      if (
        !res.data.regeocode.formatted_address ||
        res.data.regeocode.formatted_address.length == 0
      ) {
        // 如果点的位置不在国内,重置地图
        // 清空省市区
        this.cityOptions = [];
        this.regionOptions = [];
        this.streetOptions = [];
        this.Addressform = {
          provinceId: undefined,
          province: undefined,
          city: undefined,
          cityId: undefined,
          region: undefined,
          regionId: undefined,
          street: undefined,
          streetId: undefined,
          village: undefined,
        };
        this.resetForm("Addressform");
        return;
      }

      let { province, city, district, township } =
        res.data.regeocode.addressComponent;

      // 在这里为了回显,加一些判断方法
      if (province == "北京市") {
        city = "北京城区";
      } else if (province == "上海市") {
        city = "上海城区";
      } else if (province == "天津市") {
        city = "天津城区";
      } else if (province == "重庆市") {
        if (district.indexOf("区") > -1) {
          city = "重庆城区";
        } else {
          city = "重庆郊县";
        }
      }
      this.map.setZoomAndCenter(15.8, point);
      // 逐级回填省市区镇
      // 回填省
      this.provinceOptions.forEach((item) => {
        if (item.name == province) {
          this.Addressform.provinceId = item.id;
          this.Addressform.province = item.name;
        }
      });
      // 回填市 (先获取市的下拉列表)
      let res2 = await selectAreaByParentCode({
        parentId: this.Addressform.provinceId,
      });
      this.cityOptions = res2.data;
      this.cityOptions.forEach((item) => {
        if (item.name == city) {
          this.Addressform.cityId = item.id;
          this.Addressform.city = item.name;
        }
      });
      // 回填区/(先获取区/县的下拉列表)
      let res3 = await selectAreaByParentCode({
        parentId: this.Addressform.cityId,
      });
      this.regionOptions = res3.data;
      this.regionOptions.forEach((item) => {
        if (item.name == district) {
          this.Addressform.regionId = item.id;
          this.Addressform.region = item.name;
        }
      });
      // 回填镇(先获取镇的下拉列表)
      let res4 = await selectAreaByParentCode({
        parentId: this.Addressform.regionId,
      });
      this.streetOptions = res4.data;
      this.streetOptions.forEach((item) => {
        if (item.name == township) {
          this.Addressform.streetId = item.id;
          this.Addressform.street = item.name;
        }
      });
      // 回填详细信息
      this.Addressform.village =
        res.data.regeocode.formatted_address.split(township)[
          res.data.regeocode.formatted_address.split(township).length - 1
        ];
    },
    async regeoAddress(address, zoom) {
      // 获取标记位置信息:省市区镇用于保存信息
      await axios(
        `https://restapi.amap.com/v3/geocode/geo?address=${address}&key=f4d2e724f0ba6fe3b1cb5f841bce7a5e`
      ).then((res) => {
        this.map.setZoomAndCenter(
          zoom,
          res.data.geocodes[0].location.split(",")
        );
        // 给搜索的坐标打点吧 先清除原来的点
        this.setPoint(res.data.geocodes[0].location.split(","));
      });
    },
    async changeProvince(val) {
      this.provinceOptions.forEach((item) => {
        if (item.id == val) {
          this.Addressform.province = item.name;
        }
      });
      // 放大省位置
      await this.regeoAddress(this.Addressform.province, 5.5);
      // 清除市镇街道数据
      this.cityOptions = [];
      this.regionOptions = [];
      this.streetOptions = [];
      this.Addressform.cityId = undefined;
      this.Addressform.regionId = undefined;
      this.Addressform.streetId = undefined;
      this.Addressform.city = undefined;
      this.Addressform.region = undefined;
      this.Addressform.street = undefined;
      //  通过val获取子集市区
      let res = await selectAreaByParentCode({ parentId: val });
      this.cityOptions = res.data;
    },
    async changeCity(val) {
      this.cityOptions.forEach((item) => {
        if (item.id == val) {
          this.Addressform.city = item.name;
        }
      });
      await this.regeoAddress(
        this.Addressform.province + this.Addressform.city,
        8
      );
      // 镇街道数据
      this.regionOptions = [];
      this.streetOptions = [];
      this.Addressform.regionId = undefined;
      this.Addressform.streetId = undefined;
      this.Addressform.region = undefined;
      this.Addressform.street = undefined;
      //  通过val获取子集市区
      console.log(this.Addressform);
      let res = await selectAreaByParentCode({ parentId: val });
      this.regionOptions = res.data;
    },
    async changeRegion(val) {
      this.regionOptions.forEach((item) => {
        if (item.id == val) {
          this.Addressform.region = item.name;
        }
      });
      await this.regeoAddress(
        this.Addressform.province +
          this.Addressform.city +
          this.Addressform.region,
        10
      );
      // 镇街道数据
      this.streetOptions = [];
      this.Addressform.streetId = undefined;
      this.Addressform.street = undefined;
      //  通过val获取子集市区
      let res = await selectAreaByParentCode({ parentId: val });
      this.streetOptions = res.data;
    },
    async changeStreet(val) {
      this.streetOptions.forEach((item) => {
        if (item.id == val) {
          this.Addressform.street = item.name;
        }
      });
      await this.regeoAddress(
        this.Addressform.province +
          this.Addressform.city +
          this.Addressform.region +
          this.Addressform.street,
        12
      );
    },
    async searchAddress() {
      // 搜索具体位置 直接给打点
      await this.regeoAddress(
        this.Addressform.province +
          this.Addressform.city +
          this.Addressform.region +
          this.Addressform.street +
          this.Addressform.village,
        12
      );
    },
    submitAddress() {
      // 提交地址信息
      this.$refs["Addressform"].validate((valid) => {
        if (valid) {
          let address = {
            ...this.Addressform,
            longitude: this.point[0],
            latitude: this.point[1],
            farmerId: this.farmerId,
          };
          console.log(address);

          if (!address.id) {
            addFarmerAddress(address).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.MapVisible = false;
              this.$emit("updateAddress", { id: this.farmerId });
            });
          } else {
            updateFarmerAddressInfo(address).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.MapVisible = false;
              this.$emit("updateAddress", { id: this.farmerId });
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep #mapselectpoint-container {
  width: 100%;
  height: 500px;
  .amap-icon img {
    width: 30px;
    height: 40px;
  }
}
</style>

四、自定义地图

  this.map = new AMap.Map("mapselectpoint-container", {
          zoom: 15.8,
          //   center: [116.469881, 39.993599], //不设置自动定位到当前所在城市
          mapStyle: "amap://styles/8c825bfe70db32d900edb766197db660", //设置地图的显示样式
        });
        //添加如下代码即可
        this.map.setMapStyle("amap://styles/你的自定义地图ID");

私密限制

  • 1.限制key所有人都可以使用
    在这里插入图片描述
  • 2.完成上步配置后你的地图展示的将会是空白
  • 3.本地测试使用时可以将你的主机代理设置成此ip
    在这里插入图片描述
  • 4.这样地图就可以正常展示了
  • 5.如果项目中使用了webapi,将webapi转换成ajax接口,让后端去转化即可!
  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Vue3中集成高德地图,可以使用高德地图JavaScript API和Vue3的组件化开发方式相结合,来实现地图的显示和操作。 具体步骤如下: 1. 在Vue3项目中安装高德地图JavaScript API。可以通过npm安装,命令如下: ``` npm install @amap/amap-jsapi-loader --save ``` 2. 在Vue3项目中创建一个地图组件,例如Map.vue,该组件中可以嵌入高德地图的JavaScript API,以及地图容器和地图相关的操作,例如: ```vue <template> <div class="map-container" ref="mapContainer"></div> </template> <script> import { defineComponent } from 'vue' import { AMapLoader } from '@amap/amap-jsapi-loader' export default defineComponent({ name: 'Map', data() { return { map: null } }, mounted() { AMapLoader.load({ key: 'your amap key', // 高德地图API密钥 version: '2.0', plugins: ['AMap.Geolocation'], AMapUI: { version: '1.1', plugins: [] } }).then((AMap) => { this.map = new AMap.Map(this.$refs.mapContainer, { zoom: 10, center: [116.39, 39.9], resizeEnable: true }) }) } }) </script> <style scoped> .map-container { width: 100%; height: 100%; } </style> ``` 在上述代码中,使用AMapLoader加载高德地图API,然后在mounted生命周期中创建一个地图对象,并设置地图的中心点和缩放级别,最后将地图显示在组件中。 3. 在需要显示地图的页面中引入地图组件,例如: ```vue <template> <div> <Map></Map> </div> </template> <script> import Map from './Map.vue' export default { name: 'App', components: { Map } } </script> ``` 通过以上步骤,即可在Vue3项目中集成高德地图,并在页面中显示地图。需要注意的是,在使用高德地图API时,需要获取高德地图API密钥,可以在高德地图开放平台申请,申请成功后即可获得API密钥。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

库库的写代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值