Vue开发腾讯地图坐标拾取器

以前用Jquery开发过一个腾讯地图坐标拾取器,项目需要重新改成Vue版本,效果如下

大概功能描述:可以按城市及地址模糊查找位置信息,左边是查询结果,右边是地图显示,地图可以点击直接取坐标和地址信息

1、首先去申请一个key,可以在https://lbs.qq.com/这个网站里申请,需要创建一个应用并开通WebServiceAPI

 2、在vue中引用腾讯地图,在Index.html文件引入
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=您申请的Key"></script> 

3.开发坐标拾取组件

export default {
  name: "TMap",
  data() {
    return {
      visible: true,
      loading: true,
      map: null,
      mapKey: "您申请的地图Key",
      mapLevel: 14,
      mapLabel: null,
      mapCity: "",
      mapAddress: "",
      mapLatLng: null,
      searchForm: {
        key: "",
      },
      addressList: [],
      markerList: [],
      markerEventList: [],
      areaJson: [],
    };
  },
  props: {
    mapPosition: {
      type: Array,
    },
    address: {
      type: String,
    },
  },
  created() {
    this.mapLatLng = this.mapPosition;
    this.mapAddress = this.address;
    this.areaJson = areaJson.areas;
    this.$nextTick(function () {
      this.initMap();
    });
  },
  mounted() {},
  methods: {
    initMap() {
      let me = this;
      //初始化地图
      let mapContainer = document.getElementById("mapContainer");
      console.log(mapContainer);
      this.map = new window.qq.maps.Map(mapContainer, {
        zoom: me.mapLevel,
      });
      //设置Zoom
      window.qq.maps.event.addListener(this.map, "zoom_changed", function () {
        me.mapLevel = me.map.getZoom();
      });
      //创建Label
      this.mapLabel = new window.qq.maps.Label({
        map: this.map,
        offset: new window.qq.maps.Size(15, -12),
        draggable: false,
        clickable: false,
      });
      this.map.setOptions({
        draggableCursor: "crosshair",
      });

      mapContainer.addEventListener("mouseenter", function (e) {
        me.mapLabel.setMap(me.map);
      });
      mapContainer.addEventListener("mouseleave", function (e) {
        me.mapLabel.setMap(null);
      });
      window.qq.maps.event.addListener(this.map, "mousemove", function (e) {
        var latlng = e.latLng;
        me.mapLabel.setPosition(latlng);
        me.mapLabel.setContent(
          latlng.getLat().toFixed(6) + "," + latlng.getLng().toFixed(6)
        );
      });

      if (this.mapLatLng != null) {
        this.locationService();
      } else {
        this.initcityService();
      }

      //点击获取地址
      window.qq.maps.event.addListener(this.map, "click", function (e) {
        me.$jsonp(
          "http://apis.map.qq.com/ws/geocoder/v1/?location=" +
            e.latLng.getLat() +
            "," +
            e.latLng.getLng() +
            "&key=" +
            me.mapKey +
            "&output=jsonp&callback=?"
        ).then((res) => {
          console.log(res);
          if (res.status == 0) {
            me.mapAddress = res.result != undefined ? res.result.address : "";
            me.mapLatLng =
              res.result != undefined
                ? [res.result.location.lat, res.result.location.lng]
                : null;
          }
        });
      });
    },
    initcityService() {
      let me = this;
      //当位定前位置
      let cityService = new window.qq.maps.CityService({
        complete: function (result) {
          console.log(result);
          me.map.setCenter(result.detail.latLng);
          me.mapCity = result.detail.name;
        },
      });
      cityService.searchLocalCity();
    },
    //按坐标获取位置信息
    locationService() {
      let me = this;
      this.$jsonp(
        "http://apis.map.qq.com/ws/geocoder/v1/?location=" +
          this.mapLatLng[0] +
          "," +
          this.mapLatLng[1] +
          "&key=" +
          this.mapKey +
          "&output=jsonp&callback=?"
      ).then((res) => {
        if (res.status == 0 && res.result) {
          let center = new window.qq.maps.LatLng(
            this.mapLatLng[0],
            this.mapLatLng[1]
          );
          this.map.panTo(center);
          let marker = new window.qq.maps.Marker({
            position: center,
            map: this.map,
          });
          me.mapAddress = res.result.address;
          me.mapCity = res.result.address_component.city;
        }
      });
    },
    //查询地址信息
    handleSearch() {
      if (!util.isNullEmpty(this.searchForm.key)) {
        this.$jsonp(
          "http://apis.map.qq.com/ws/place/v1/search?keyword=" +
            this.searchForm.key +
            "&boundary=region(" +
            this.mapCity +
            ",0)&page_size=9&page_index=1&key=" +
            this.mapKey +
            "&output=jsonp&&callback=?"
        ).then((res) => {
          console.log(res);
          if (res.status == 0) {
            res.data.map((item, index) => {
              item.id = "mapItem" + index;
              item.active = false;
              item.hover = false;
              return item;
            });
            this.addressList = res.data;
            this.setMarker(res);
            this.map.setZoom(14);
          }
        });
      } else {
        this.addressList = [];
        this.$jsonp(
          "http://apis.map.qq.com/ws/geocoder/v1/?region=" +
            this.mapCity +
            "&address=" +
            this.mapCity +
            "&key=" +
            this.mapKey +
            "&output=jsonp&&callback=?"
        ).then((res) => {
          if (res.status == 0) {
            this.map.setCenter(
              new window.qq.maps.LatLng(
                res.result.location.lat,
                res.result.location.lng
              )
            );
            this.map.setZoom(14);
          }
        });
      }
    },
    //设置Marker
    setMarker(res) {
      let me = this;
      let latlngBounds = new window.qq.maps.LatLngBounds();
      //删除Marker
      this.markerList.forEach((item) => {
        item.setMap(null);
      });
      //删除Marker事件
      this.markerEventList.forEach((item) => {
        window.qq.maps.event.removeListener(item);
      });

      this.markerEventList = [];
      this.markerList = [];
      res.data.forEach((item, index) => {
        let latlng = new window.qq.maps.LatLng(
          item.location.lat,
          item.location.lng
        );
        latlngBounds.extend(latlng);
        //创建Marker
        let marker = new window.qq.maps.Marker({
          map: this.map,
          position: latlng,
          zIndex: 10,
        });
        marker.index = index;
        marker.isClicked = false;
        this.setAnchor(marker, false);
        this.markerList.push(marker);
        //点击事件
        this.markerEventList.push(
          window.qq.maps.event.addDomListener(marker, "click", function () {
            me.setFlagClicked(this.index);
          })
        );
        this.markerEventList.push(
          window.qq.maps.event.addDomListener(marker, "mouseover", function () {
            me.setCurrentMarker(this.index, true);
            me.hoverAddress(this.index, true);
            me.mapLabel.setContent(
              this.position.getLat().toFixed(6) +
                "," +
                this.position.getLng().toFixed(6)
            );
            me.mapLabel.setPosition(this.position);
            me.mapLabel.setOptions({
              offset: new window.qq.maps.Size(15, -20),
            });
            document
              .getElementById("mapItem" + this.index)
              .scrollIntoView({ behavior: "smooth" });
          })
        );
        this.markerEventList.push(
          window.qq.maps.event.addDomListener(marker, "mouseout", function () {
            me.setCurrentMarker(this.index, false);
            me.hoverAddress(this.index, false);
            me.mapLabel.setOptions({
              offset: new window.qq.maps.Size(15, -12),
            });
          })
        );
        this.map.fitBounds(latlngBounds);
      });
      if (this.markerList.length > 0) {
        this.map.setCenter(this.markerList[0].position);
      }
    },
    setAnchor(marker, flag) {
      let left = marker.index * 27;
      let anchor = new window.qq.maps.Point(10, 30),
        origin = new window.qq.maps.Point(left, flag ? 35 : 0),
        size = new window.qq.maps.Size(27, 33),
        icon = new window.qq.maps.MarkerImage(
          "/images/marker10.png",
          size,
          origin,
          anchor
        );
      marker.setIcon(icon);
    },
    //选择地址
    selectAddress(index) {
      this.setCurrentAddress(index);
      this.setFlagClicked(index);
      this.map.setCenter(this.markerList[index].position);
    },
    hoverAddress(mapIndex, flag) {
      this.addressList.map((item, index) => {
        item.hover = flag ? index == mapIndex : flag;
        return item;
      });
    },
    setCurrentAddress(mapIndex) {
      this.addressList.map((item, index) => {
        item.active = index == mapIndex;
        return item;
      });
    },
    setCurrentMarker(index, flag) {
      if (flag || (!flag && !this.markerList[index].isClicked)) {
        this.setAnchor(this.markerList[index], flag);
      }
    },
    setFlagClicked(mapIndex) {
      this.markerList.map((item, index) => {
        if (index == mapIndex) {
          item.isClicked = true;
          item.setZIndex(10);
          this.setAnchor(item, true);
          this.mapLatLng = [
            item.getPosition().getLat().toFixed(6),
            item.getPosition().getLng().toFixed(6),
          ];
          this.mapAddress = this.addressList[mapIndex].address;
        } else {
          item.isClicked = false;
          item.setZIndex(9);
          this.setAnchor(item, false);
        }
        return item;
      });
      this.setCurrentAddress(mapIndex);
      document
        .getElementById("mapItem" + mapIndex)
        .scrollIntoView({ behavior: "smooth" });
    },
    handleSubmit() {
      if (this.mapLatLng == null) {
        this.$message({
          message: "请定位坐标",
          type: "error",
          offset: 60,
        });
        return;
      }
      this.$emit("setMap", { position: this.mapLatLng,address:this.mapAddress });
    },
    //关闭
    closeMapWin() {
      this.$emit("closeMapWin", {});
    },
  },
};

4.该例子有用到ElementUI和jsonp

效果Demo可以访问http://demo.h5qr.cn/map

完整代码库https://github.com/xi-star/vuemap

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值