vue-amap实现实现初始化并定位当前位置,搜索,定位,增加点标记

23 篇文章 0 订阅
3 篇文章 0 订阅

实现如图展示,初始化并定位当前位置,搜索,定位,增加点标记
在这里插入图片描述
下载vue

1.vue页设置

  • 如果是新版web-js的密钥,有配套的安全秘钥,则需要另外在created加入,否则会报undefined
window._AMapSecurityConfig = {
                securityJsCode:'你的安全秘钥',
            }
<template>
    <div class="bg-body" style="min-width: 1100px">
       

                                  <el-input class="mgt10" v-model="showName" placeholder="请选择地图" @change="searchLng">
                                      <template slot="suffix">
                                          <i @click="showDialog" class="el-icon-location-information"></i>
                                      </template>
                                  </el-input>
                                
        <el-dialog title="选择地点" :visible.sync="dialogFormVisible">
            <div style="height: 400px;width: 100%">

                <div class="flex-l-b">
                    <el-amap-search-box class="search-box" :search-option="searchOption"
                                        :on-search-result="onSearchResult"></el-amap-search-box>
                    <span class="mgl10">{{form.address}}{{form.longitude}},{{form.latitude}}</span>
                    <el-button type="primary" @click="sureMap">确定</el-button>
                </div>
                <div>
                    <base-map-search
                            ref="mapSearch"
                            :city="form.city"
                            :value="form.address"
                            :longitude="form.longitude"
                            :latitude="form.latitude"
                            :isEdit="isEdit"
                            :center="center"
                            @updateLocation="updateLocation"
                    />
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
   
    import BaseMapSearch from '@/components/pd/common/map'
    import axios from 'axios'
    import Vue from 'vue'
    import VueAMap from 'vue-amap';
    Vue.use(VueAMap);
    VueAMap.initAMapApiLoader({
        // 高德的key
        key: '你的key',
        // 插件集合
        plugin: ['AMap.Autocomplete','AMap.Geolocation', 'AMap.AMapUI', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor','AMap.Geocoder','AMap.CitySearch'],
        // 高德 sdk 版本,默认为 1.4.4
        v: '1.4.4'
    });

    export default {
        name: "add-station",
        components: {
            BaseMapSearch,
        },
        data () {
            return {
                editPlantObj:{},
                editPlantId:'',
                //地图
                // tan:false,//地图判断是否
                isEdit:false,//地图判断是否
                center: [112.320331, 40.012928],
                form2:{
                    province:'',
                    city:'',
                    county:'',
                    imei:'',
                    deviceType:"",
                    plantName:"",
                    address: '',
                    lang:'zh',
                },
                form: {
                    address: '',
                    longitude: '',
                    latitude: '',
                    provinceCode:'',
                    cityCode:'',
                    countyCode:'',
                },

                dialogFormVisible: false,


                form1:{
                    province:'',
                    city:'',
                    county:'',
                    imei:'',
                    deviceType:"",
                    plantName:"",
                    address: '',
                    lang:'zh',
                },
                url:'https://www.baidu.com/',
      
            }
        },
        computed:{
          showName(){
              return this.form1.province + this.form1.city+this.form1.county
          }
        },
        //form的address是完整的,form1.address是详细地址
        methods: {
            //展示地图
            showDialog(){
                if(this.editPlantId){
                    this.isEdit=true
                    this.searchLng()
                }
                this.dialogFormVisible=true

            },
            
            checkData(data){
                this.editPlantObj=data
                this.form1=data
                this.form1.address=data.address
                this.form.address=data.province+data.city+data.county+data.address

                this.secondTab=data.deviceList


            },
      
            //填写详细地址后,请求经纬度
            searchLng(){
                let key='你的key'
                axios.get(`https://restapi.amap.com/v3/geocode/geo?key=${key}&s=rsv3&city=35&address=${this.form.address}`)
                    .then( (response) => {
                    

                        // this.$alert('已根据填写信息定位,如有偏差,请自行点击地图选取!', '确认地址', {
                        //   confirmButtonText: '确定',
                        //   callback: action => {
                        //     this.dialogFormVisible=true
                        //   }
                        // });
                    })
                    .catch( (error) => {
                        console.log(error)
                        // this.dialogFormVisible=false
                    });
            },
            sureMap(){
                let key='你的key'
                axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${key}&s=rsv3&city=35&location=${this.form.longitude+','+this.form.latitude}`)
                    .then( (response) => {
                        console.log(response)
                       
                        this.form1.address=response.data.regeocode.formatted_address.substring(this.showName.length)
                        // //取出选择器
                        // let item={
                        //     cityCode:obj.adcode.substring(0,4),
                        //     city:obj.city,
                        //     countyCode:obj.adcode.substring(0,6),
                        //     county:obj.district,
                        //     index:0
                        // }
                        // //两种情况,一种选择地址后 地图取点。一种是直接取点,
                        // this.reqNextArea(provinceCode,'cityList',item)
                        //
                        // //详细地址
                        // let str=obj.province+obj.city+obj.district
                        // this.formData.detailAddress=response.data.regeocode.formatted_address.substring(str.length)
                        // console.log(response.data.geocodes);
                        // let location=obj.location.split(',')
                        // console.log(location)
                        // this.form.longitude = location[0]
                        // this.form.latitude = location[1]
                        // this.form.address = this.showName
                        this.center = [this.form.longitude, this.form.latitude]
                        this.isEdit=false

                    })
                    .catch( (error) => {
                        console.log(error);
                    });
                this.dialogFormVisible=false
            },
            // 地图搜索选址
            updateLocation(lng, lat, address) {
                this.form.longitude = lng
                this.form.latitude = lat
                this.form.address = address
                this.center = [lng, lat]
            },

          
            searchOption(pois) {
                console.log(pois)
            },
            onSearchResult(pois) {
                //点击搜索后触发的事件
                this.input = document.querySelector('.search-box-wrapper input').value
                //这边类似模糊查询 会返回一个数组,我就直接取第一个值了。
                this.center = [pois[0].lng, pois[0].lat]
                this.form.longitude = pois[0].lng
                this.form.latitude = pois[0].lat
                this.form.address = pois[0].address

            },
          
            handleClick(tab, event) {
                console.log(tab, event);
            },

            onSubmit() {
                console.log('submit!');
            }
        },
       
    }
</script>

<style lang="scss">
  .search-box {
    margin-top: 6px;
    width: 100%;
  }
  .el-vue-search-box-container {
    /*width: 100% !important;*/
    margin-bottom: 10px;
  }
  .search-box input {
    padding: 0 15px;
    width: 100%;
    height: 32px;
    line-height: 32px;
    color: #606266;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
  .search-box input:focus {
    border-color: #409eff;
    outline: 0;
  }
  .search-box input::-webkit-input-placeholder {
    color: #c0c4cc;
  }
  .tip-box {
    width: 100%;
    max-height:280px;
    position: absolute;
    top: 72px;
    z-index: 10000;
    overflow-y: auto;
    background-color: pink;
  }
</style>

子组件设置

<template>
  <div style="height:300px">

        <!--
          amap-manager: 地图管理对象
          vid:地图容器节点的ID
          zooms: 地图显示的缩放级别范围,在PC上,默认范围[3,18],取值范围[3-18];在移动设备上,默认范围[3-19],取值范围[3-19]
          center: 地图中心点坐标值
          plugin:地图使用的插件
          events: 事件
        -->
    <div class="amap-box">
      <el-amap
        :amap-manager="amapManager"
        :vid="'amap-vue'"
        :zoom="zoom"
        :plugin="plugin"
        :center="center"
        :events="events"
      >
        <!-- 标记 -->
        <el-amap-marker
          v-for="(marker, index) in markers"
          :position="marker"
          :key="index"
        ></el-amap-marker>
      </el-amap>
    </div>
  </div>
</template>
<script  type="text/javascript" src="https://webapi.amap.com/maps?v=2.0;key=你的key&plugin=AMap.Geolocation"></script>
//不记得是为什么添加这个了


<script>

  import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";
  let amapManager = new AMapManager();
  export default {
    props: ["city", "value", "longitude", "latitude", "isEdit", "center"],
    data() {
      let self = this;
      return {
        address: null,
        searchKey: "",
        amapManager,
        markers: [],
        searchOption: {
          city: this.city ? this.city : "全国",
          citylimit: true
        },
        // center: [121.329402, 31.228667],
        zoom: 17,
        lng: 0,
        lat: 0,
        loaded: false,
        events: {
          init() {
            lazyAMapApiLoaderInstance.load().then(() => {
              // self.initSearch();
            });
          },
          // 点击获取地址的数据
          click(e) {
            console.log(e)
            self.markers = [];
            let { lng, lat } = e.lnglat;
            self.lng = lng;
            self.lat = lat;
            self.center = [lng, lat];
            self.markers.push([lng, lat]);
            // 这里通过高德 SDK 完成。
            let geocoder = new AMap.Geocoder({
              radius: 10000,
              extensions: "all"
            });
            geocoder.getAddress([lng, lat], function(status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  self.address = result.regeocode.formattedAddress;
                  self.searchKey = result.regeocode.formattedAddress;
                  self.$emit("updateLocation", lng, lat, self.searchKey);
                  self.$nextTick();
                }
              }
            });
          }
        },
        // 一些工具插件
        plugin: [
          {
            // 定位
            showMaker:true,
            pName: "Geolocation",
            events: {
              init(o) {
                // o是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  if (result && result.position) {
                    if (self.isEdit) {
                      // 设置经度
                      self.lng = self.longitude;
                      // 设置维度
                      self.lat = self.latitude;
                      // 设置坐标
                      self.center = [self.longitude, self.latitude];
                      self.markers.push([self.longitude, self.latitude]);
                    } else {
                      // 设置经度
                      self.lng = result.position.lng;
                      // 设置维度
                      self.lat = result.position.lat;
                      // 设置坐标
                      self.center = [self.lng, self.lat];
                      self.markers.push([self.lng, self.lat]);
                      self.$emit("updateLocation", self.lng, self.lat, result.formattedAddress);
                    }
                    // load
                    self.loaded = true;
                    // 页面渲染好后
                    self.$nextTick();
                  }
                });

              }
            }
          },{
            // 定位城市
            pName: "CitySearch",
            events: {
              init(o) {
                // o是高德地图定位插件实例
                o.getLocalCity(function(status, result) {
                  if (status === "complete" && result.info === "OK") {
                    // 查询成功,result即为当前所在城市信息
                    console.log(result)
                  }
                });
              }
            }
          },
        ]
      };
    },
    created() {
      console.log(this.center)
      console.log(this.value)
      this.getLocation()

      if (this.value) {
        console.log(this.center)
        this.searchKey = this.value;
        this.address = this.value;
        this.markers.push(this.center);
      }
      if (this.longitude && this.latitude) {
        this.lng = this.longitude;
        this.lat = this.latitude;
        this.center = [this.longitude, this.latitude];
        this.markers.push([this.longitude, this.latitude]);
      }
      if(this.center){
        this.markers.push(this.center);
      }
    },
    methods: {
      getLocation() {
        const that = this;
        AMap.plugin("AMap.Geolocation", function() {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位,默认:true
            enableHighAccuracy: true,
            // 设置定位超时时间,默认:无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: "RB"
          });

          geolocation.getCurrentPosition();
          AMap.event.addListener(geolocation, "complete", onComplete);
          AMap.event.addListener(geolocation, "error", onError);

          function onComplete(data) {
            // data是具体的定位信息
            console.log(data);
          }

          function onError(data) {
            // 定位出错
            console.log(data);
            // 失败之后调用这个方法,使用IP定位获取当前城市信息
            that.getLngLatLocation();
          }
        });
      },
      // IP定位获取当前城市信息
      getLngLatLocation() {
        AMap.plugin("AMap.CitySearch", function() {
          var citySearch = new AMap.CitySearch();
          citySearch.getLocalCity(function(status, result) {
            if (status === "complete" && result.info === "OK") {
              // 查询成功,result即为当前所在城市信息
              console.log(result)
            }
          });
        });
      },
      searchOption(pois){
        console.log(pois)
      },
      onSearchResult(pois){
        //点击搜索后触发的事件
        this.input = document.querySelector(".search-box-wrapper input").value
        //这边类似模糊查询 会返回一个数组,我就直接取第一个值了。
        this.center = [pois[0].lng, pois[0].lat];
        this.markers.push([pois[0].lng, pois[0].lat]);
      },
      // 选择地址后自动定位到当前地址附近
      updateAddress(value, longitude, latitude) {
        this.searchKey = value;
        this.address = value;
        this.lng = longitude;
        this.lat = latitude;
        this.center = [longitude, latitude];
        this.markers.push([longitude, latitude]);
      },
      initSearch() {
        let vm = this;
        let map = this.amapManager.getMap();
        AMapUI.loadUI(["misc/PoiPicker"], function(PoiPicker) {
          console.log(PoiPicker)
          let poiPicker = new PoiPicker({
            input: "search",
            placeSearchOptions: {
              map: map,
              pageSize: 10
            },
            suggestContainer: "searchTip",
            searchResultsContainer: "searchTip"
          });
          vm.poiPicker = poiPicker;
          // 监听poi选中信息
          poiPicker.on("poiPicked", function(poiResult) {
            let source = poiResult.source;
            let poi = poiResult.item;
            if (source !== "search") {
              poiPicker.searchByKeyword(poi.name);
            } else {
              poiPicker.clearSearchResults();
              vm.markers = [];
              let lng = poi.location.lng;
              let lat = poi.location.lat;
              let address = poi.name; // poi.cityname + poi.adname + poi.name
              vm.center = [lng, lat];
              vm.markers.push([lng, lat]);
              vm.lng = lng;
              vm.lat = lat;
              vm.address = address;
              vm.searchKey = address;
              vm.$emit("updateLocation", lng, lat, vm.searchKey);
            }
          });
        });
      },
      searchByHand() {
        console.log('zh ')
        // if (this.searchKey !== "" && this.poiPicker) {

          this.poiPicker.searchByKeyword(this.searchKey);
        // }
      }
    },
    watch:{
      center:function(val) {
        this.markers.push(val);
      }
    }
  };
</script>
<style lang="scss">
  .search-box {
    margin-top: 6px;
    width: 100%;
  }
  .el-vue-search-box-container {
    /*width: 100% !important;*/
    margin-bottom: 10px;
  }
  .search-box input {
    padding: 0 15px;
    width: 100%;
    height: 32px;
    line-height: 32px;
    color: #606266;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
  .search-box input:focus {
    border-color: #409eff;
    outline: 0;
  }
  .search-box input::-webkit-input-placeholder {
    color: #c0c4cc;
  }
  .tip-box {
    width: 100%;
    max-height:280px;
    position: absolute;
    top: 72px;
    z-index: 10000;
    overflow-y: auto;
    background-color: pink;
  }
</style>
<style>
  .amap-ui-poi-picker-sugg,
  .amap_lib_placeSearch {
    border: 1px solid #eee;
    border-radius: 4px;
  }
  .amap-box {
    height: inherit;
  }

</style>

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要在Vue项目中使用vue-amap,首先需要安装vue-amap模块。可以通过npm命令来安装: ``` npm install vue-amap --save ``` 安装完成后,在Vue项目的入口文件中引入vue-amap模块,并进行初始化: ``` import VueAMap from 'vue-amap'; Vue.use(VueAMap); VueAMap.initAMapApiLoader({ // 高德的key key: 'your amap key', // 插件集合 plugin: ['AMap.Geolocation', 'AMap.MarkerClusterer'], // 高德 sdk 版本,默认为 1.4.15 v: '1.4.15', }); ``` 其中,`your amap key`需要替换成你自己的高德地图应用的key。 接下来,在组件中引入`vue-amap`的组件,并使用`amap`标签来显示地图: ``` <template> <div> <amap :zoom="zoom" :center="center"> <amap-marker :position="center"></amap-marker> </amap> </div> </template> <script> export default { data() { return { zoom: 13, center: [116.397428, 39.90923], }; }, }; </script> ``` 以上代码实现了在Vue组件中显示一个地图,并在地图上显示一个标记。具体使用方式可以参考vue-amap的文档。 ### 回答2: Vue-amap 是一个基于Vue高德地图组件库,可以方便地在Vue项目中使用高德地图服务。 要使用vue-amap,需要按照以下步骤进行操作: 1. 首先,安装vue-amap库。可以通过npm或者yarn来进行安装。在终端中执行以下命令: ``` npm install --save vue-amap ``` 或者 ``` yarn add vue-amap ``` 2. 在Vue项目的入口文件(通常是main.js)中,引入vue-amap并注册为Vue的插件。在代码中添加以下内容: ```javascript import VueAMap from 'vue-amap'; Vue.use(VueAMap); ``` 3. 在需要使用高德地图的组件中,可以通过`VueAMap.initAMapApiLoader`方法进行配置和初始化。在代码中添加以下内容: ```javascript VueAMap.initAMapApiLoader({ key: 'your-amap-key', // 高德地图API的key // 插件集合 plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.Geolocation'], // 高德地图 SDK 版本,默认为 1.4.4 v: '1.4.4' }); ``` 在这里,需要将`your-amap-key`替换为你申请到的高德地图API的key。 4. 然后,就可以在组件中使用vue-amap提供的地图组件了。例如,在组件的模板中添加以下内容: ```html <vue-amap id="mapContainer" :zoom="13" :center="['116.397428', '39.90923']"> <div class="amap-marker" :position="['116.397428', '39.90923']"></div> </vue-amap> ``` 在这里,使用`vue-amap`标签来包裹地图组件,并通过`:zoom`和`:center`属性设置地图缩放级别和中心。在`vue-amap`标签内,可以添加其他地图相关的组件。 这样,就可以在Vue项目中使用vue-amap来显示高德地图了。在实际开发中,还可以根据需要使用vue-amap提供的其他功能和API来实现更多的地图操作和交互。 ### 回答3: Vue-amap是一个基于Vue.js高德地图组件库,提供了丰富的地图展示和操作功能。要使用vue-amap,首先需要在项目中安装它。 1. 在项目目录下打开终端,运行以下命令来安装vue-amap: ``` npm install vue-amap --save ``` 2. 在需要使用地图的组件中,引入vue-amap: ```javascript import AMap from 'vue-amap'; ``` 3. 调用Vue.use()方法并添加参数AMap: ```javascript Vue.use(AMap); ``` 4. 在项目的入口文件(main.js)中,加载高德地图的SDK: ```javascript AMap.initAMapApiLoader({ key: 'your-amap-api-key', plugin: ['AMap.Geolocation'] }); ``` 注意:replace 'your-amap-api-key'为你注册高德地图开发者账号后获得的API Key。 5. 在组件的template中,使用vue-amap提供的地图组件: ```html <template> <div> <amap-map :zoom="13" :center="[lng, lat]"> <amap-marker :position="[lng, lat]"></amap-marker> </amap-map> </div> </template> ``` 上述代码展示了一个简单的地图,包含一个标记在指定的经纬度上。 至此,我们已经完成了vue-amap的基本配置,可以在Vue项目中使用高德地图的各种功能了。根据官方文档,还可以使用更多的组件和API来控制地图的交互、显示等,以满足具体需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值