Tencent location service + element-ui realizes address search & marker marking function

Preface

The mini program project needs to realize the input address search to resolve the corresponding latitude and longitude and mark it on the map.

Preliminary preparation

1. Apply for Tencent location service key

2、npm install qqmap --save

Introduce the required js files

Enter in App.vue

<script type="text/javascript" src="http://map.qq.com/api/js?v=2.exp&key=申请的key"></script>
<script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>

Create a new TMap.js file

import maps from 'qqmap';

export function TMap() {
    return new Promise(resolve => {
        maps.init(申请的key, () => {
            resolve(maps);
        });
    });
}

Create a new map.vue file

<template>
  <div id="container"></div>
</template>
<script>
/* eslint-disable */
import { TMap } from "./TMap"; 

export default {
  name: "mapChild",
  data() {
    return {};
  },
  created() {
    let _this = this;
    TMap().then(qq => {
      //初始化中心点,传入想要设置的值
      this.mapInit(经度, 纬度, 缩放比例);
    });
  },
  methods: {
    //父组件调用该函数,设置地点
    setLoc(lng, lat) {
      this.mapInit(lng, lat, 16);
    },
    //搜索某一地点名
    getLoc(ele) {
      this.$axios({
        url: url, 
        //直接使用腾讯的搜索api的话会报跨域错误
        //我是通过node服务端作为代理去请求数据
        //所以这里就不放出实际ip地址了哈
        //在最后我会将node部分的代码也加上
        method: "get",
        params: {
          address: ele
        }
      })
        .then(res => {
          let searchObj = res.data.data;
          searchObj.search = 1;
          this.$emit("mapSend", searchObj);
          let _this = this;
          let resultData = res.data.data.data[0];
          if (res.data.data.status == 0) {
            this.mapInit(resultData.location.lng, resultData.location.lat, 16);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    //根据传入的值渲染地图及传出经纬度和地名
    mapInit(lng,lat,zoom) {
      let _this = this
      var map = new qq.maps.Map(document.getElementById("container"), {
        // 地图的中心地理坐标。
        center: new qq.maps.LatLng(
          lat,
          lng
        ),
        zoom: zoom
      });
      var marker = new qq.maps.Marker({
        position: new qq.maps.LatLng(
          lat,
          lng
        ),
        map: map
      });
      qq.maps.event.addListener(map, "click", function(event) {
        marker.setMap(null);
      });
      qq.maps.event.addListener(map, "click", function(event) {
        let result = {
          status: 0,
          result: {
            location: {
              lng: event.latLng.getLng(),
              lat: event.latLng.getLat()
            }
          }
        };
        qq.maps.event.addListener(map, "click", function(event) {
          marker.setMap(null);
        });
        var marker = new qq.maps.Marker({
          position: event.latLng,
          map: map
        });

        _this
          .$axios({
            url: url,
            //这里的url跟上面也是相同的问题
            method: "get",
            params: {
              location: event.latLng.getLat() + "," + event.latLng.getLng()
            }
          })
          .then(res => {
            res.data.data.extra = 1;
            _this.$emit("mapSend", res.data.data);
          })
          .catch(err => {
            this.$message({
              type: 'warning',
              message: '定位解析失败'
            })
          })
      });
    }
  },
};
</script>
<style>
#container {
  min-width: 600px;
  min-height: 400px;
}
</style>

The above completes the creation of the child component, and then it can be introduced and used in the parent component

Effect picture

Insert picture description here

node code

//获取地点
router.get('/tmapA', async function (req, res, next) {
    let url = 'http://apis.map.qq.com/ws/place/v1/suggestion/?key=申请的key&region=' + urlencode('绍兴','utf-8') + '&keyword=' + urlencode(req.query.address,'utf-8') 
    request({
        url: url,
        method: "GET",
        json: true,
    }, function(_err, _res, _resBody){        
        if(_resBody){
            new Result(_resBody, '解析成功').success(res)
        }else{
            new Result(null, '解析失败').fail(res)
        }
    })
})
//获取经纬度
router.get('/tmapL', async function (req, res, next) {
    let url = 'https://apis.map.qq.com/ws/geocoder/v1/?key=申请的key&location=' + req.query.location
    request({
        url: url,
        method: "GET",
        json: true,
    }, function(_err, _res, _resBody){        
        if(_resBody){
            new Result(_resBody, '解析成功').success(res)
        }else{
            new Result(null, '解析失败').fail(res)
        }
    })
})

Author: yiyou12138

Link: https://segmentfault.com/a/1190000022763174

Source: SegmentFault

The copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_45628602/article/details/111661342