您的位置:首页 > 汽车 > 时评 > web端使用高德地图

web端使用高德地图

2024/7/2 4:24:57 来源:https://blog.csdn.net/weixin_45580774/article/details/139660532  浏览:    关键词:web端使用高德地图

web端使用高德地图

    • 一、申请高德key和秘钥
    • 二、在项目中引入所需功能js、css文件
    • 三、实现地图选点、回显选点
    • 四、自定义地图

一、申请高德key和秘钥

  • 申请高德key
    在这里插入图片描述
  • 申请成功后可以得到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" />
<scripttype="text/javascript"src="https://webapi.amap.com/demos/js/liteToolbar.js"
></script>

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

<template><el-dialog title="选择地址" :visible.sync="MapVisible" width="960px"><el-formref="Addressform":model="Addressform":rules="Addressrules"label-width="65px"><el-row><el-col :span="6"><el-form-item label="省" prop="province"><el-selectv-model="Addressform.provinceId"placeholder=""filterablestyle="width: 100%"@change="changeProvince"><el-optionv-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-selectv-model="Addressform.cityId"filterableplaceholder=""style="width: 100%"@change="changeCity"><el-optionv-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-selectv-model="Addressform.regionId"placeholder=""filterablestyle="width: 100%"@change="changeRegion"><el-optionv-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-selectv-model="Addressform.streetId"placeholder=""filterablestyle="width: 100%"@change="changeStreet"><el-optionv-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-inputtype="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-buttontype="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-buttontype="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",// 图片 urlimage:"https://a.amap.com/jsapi_demos/static/demo-center/marker/express2.png",// 图片尺寸size: [64, 30],// 图片相对 position 的锚点,默认为 bottom-centeranchor: "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");

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com