uniapp map 显示位置通用组件

由于APP 端 map层级高于普通层级,h5仅不支持高德,所以单独抽一个组件用于地图组件兼容

1、h5 高德js请在index.html中引入,请参照 https://blog.csdn.net/weixin_43073383/article/details/122359123
2、app使用
组件components/aMapRs.vue
通过获取当前页面栈 webview.appendJsFile ,提前载入amapjs ,然后 onlaod之后,去执行h5高德地图逻辑
3、小程序setCenter有点问题,此处用v-if,可暂时忽略

<template>
  <div class="aMap">
    <!-- #ifndef MP -->
    <div
      :id="_mid"
      :ref="_mid"
      :style="{
        width: config.width,
        height: config.height,
        position: relative,
      }"
    ></div>
    <a-icon
      src="current_address.png"
      heightS="16px"
      class="current_address icon"
      @tap.stop="setCenter"
    />
    <!-- #endif -->
    <!-- #ifdef MP -->
    <map
      v-if="show"
      id="map"
      class="map"
      :style="{
        width: config.width,
        height: config.height,
      }"
      :show-location="true"
      :latitude="config.latitude"
      :longitude="config.longitude"
      :markers="markers"
    >
      <cover-image
        class="current_address icon"
        @tap="setCenter"
        src="https://yjy.yiyiny.com/static/images/20221122/icons/current_address.png"
      ></cover-image>
    </map>
    <!-- #endif -->
  </div>
</template>

<script>
import ab_ from "axj-ab_";
import abUni from "@/script/ablib/engin/abUni";
export default {
  name: "aMap",
  props: {
    config: {
      type: Object,
      default: {
        width: "100%",
        height: "300rpx",
        longitude: 118.78025,
        latitude: 31.972952,
      },
    },
  },
  watch: {
    config() {
      this.refresh();
    },
  },
  data() {
    return {
      _mid: "aMap_" + ab_.nextT(),
      // config: {},
      map: null,
      webview: null,
      markers: [],
      show: true,
      active: true,
      activeRefresh: false,
    };
  },
  mounted() {
    // #ifdef APP-PLUS
    let webview = abUni.page().$getAppWebview();
    console.log(webview);
    this["$webView"] = webview;
    if (webview && !webview["aMapRsInjected"]) {
      webview["aMapRsInjected"] = true;
      webview.appendJsFile("./static/map/amap.js");
    }
    this.webview = webview;
    this.refresh(webview);
    // #endif
    // #ifdef H5 || MP
    this.refresh();
    // #endif
  },
  //解决全局变量出发 keeplive问题,单独引入可不写
  activated() {
    this.active = true;
    if (this.activeRefresh) {
      this.refresh();
    }
  },
  //解决全局变量出发 keeplive问题,单独引入可不写
  deactivated() {
    this.active = false;
  },
  //解决全局变量出发 keeplive问题,单独引入可不写
  lifetimes: {
    attached() {
      this.active = true;
      if (this.activeRefresh) {
        this.refresh();
      }
    },
    detached() {
      this.active = false;
    },
  },
  methods: {
    refresh(webview) {
      this.activeRefresh = false;
      let self = this;
      // #ifdef APP-PLUS
      if (!webview) {
        webview = this.webview;
      }
      setTimeout(function () {
        webview.evalJS(
          `aMapRsRefresh('${self._mid}', '${JSON.stringify(self.config)}')`
        );
      }, 100);
      // #endif
      // #ifdef H5
      self.aMapRsRefresh(self._mid, self.config);
      // #endif
      // #ifdef MP
      self.markers = [
        {
          id: 1,
          longitude: self.config.longitude,
          latitude: self.config.latitude,
          // iconPath: "../../images/all.png",
          width: 20,
          height: 30,
        },
      ];
      // #endif
    },
    // #ifdef H5
    aMapRsRefresh(id, config) {
      let self = this;
      AMapUI.loadUI(["misc/PositionPicker"], function (PositionPicker) {
        if (!self.active || !document.getElementById(id)) {
          self.activeRefresh = true;
          return;
        }

        var map = new AMap.Map(id, {
          enableHighAccuracy: true, //是否使用高精度定位,默认:true
          zoomToAccuracy: true,
          zoom: 13, //缩放级别 5, 7 ,13
          scrollWheel: false,
          dragEnable: true, //是否可拖动
          resizeEnable: true,
          rotateEnable: true,
          center: self.config.longitude
            ? [self.config.longitude, self.config.latitude]
            : [118.78025, 31.972952], //初始化地图中心点
          mapStyle: "amap://styles/fresh",
          features: ["bg", "road", "building", "point"],
        });
        var marker = new AMap.Marker({
          position: new AMap.LngLat(
            self.config.longitude,
            self.config.latitude
          ), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
          title: "默认图标",
        });
        // marker.on("click",handleMapLocation);
        map.add(marker);
        map.panBy(0, 1);
        self.map = map;
      });
    },
    // #endif
    setCenter() {
      // #ifdef MP
      this.show = false;
      setTimeout(() => {
        self.show = true;
      }, 300);
      // let _mapContext = uni.createMapContext("map", this);
      // _mapContext.moveToLocation({
      //   longitude: this.config.longitude,
      //   latitude: this.config.latitude,
      //   complete: (res) => {
      //     console.log("setCenter3", res);
      //   },
      // });
      // #endif
      // #ifdef H5
      this.map.setCenter(
        this.config.longitude
          ? [this.config.longitude, this.config.latitude]
          : [118.78025, 31.972952]
      );
      // #endif
      // #ifdef APP-PLUS
      this.webview.evalJS(`setMapCenter('${JSON.stringify(this.config)}')`);
      // #endif
    },
  },
};
</script>
<style lang="scss">
.aMap {
  position: relative;
}
.current_address {
  width: 30rpx;
  height: 30rpx;
  position: absolute;
  bottom: 10rpx;
  right: 10rpx;
  z-index: 999;
}
</style>


amap.js

(function () {
  var amapRes = null;
  var flage = 0;
  function addScript(url, fun) {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", url);
    document.getElementsByTagName("body")[0].appendChild(script);
    if (fun) script.onload = fun;
  }
  addScript(
    "https://webapi.amap.com/maps?v=1.4.15&key=您的高德key",
    function () {
      flage++;
      addScript("https:webapi.amap.com/ui/1.0/main.js", function () {
        flage++;
      });
    }
  );
  // 增加设置中心点功能
  window.setMapCenter = function (config) {
    if (config && typeof config == "string") {
      config = JSON.parse(config);
    }
    amapRes.setCenter(
      config.longitude
        ? [config.longitude, config.latitude]
        : [118.78025, 31.972952]
    );
  };
  window.aMapRsRefresh = function (id, config) {
	console.log('flage',flage)
	if(flage<2){
		setTimeout(() => {
		   window.aMapRsRefresh(id, config);
		}, 300);
		 return;
	}
    AMapUI.loadUI(["misc/PositionPicker"], function (PositionPicker) {
      if (config && typeof config == "string") {
        config = JSON.parse(config);
      }
      var map = new AMap.Map(id, {
        enableHighAccuracy: true, //是否使用高精度定位,默认:true
        zoomToAccuracy: true,
        zoom: 13, //缩放级别 5, 7 ,13
        scrollWheel: false,
        dragEnable: true, //是否可拖动
        resizeEnable: true,
        rotateEnable: true,
        center: config.longitude
          ? [config.longitude, config.latitude]
          : [118.78025, 31.972952], //初始化地图中心点
        mapStyle: "amap://styles/fresh",
        features: ["bg", "road", "building", "point"],
      });
      var marker = new AMap.Marker({
        position: new AMap.LngLat(config.longitude, config.latitude), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
        title: "默认图标",
      });
      // marker.on("click",handleMapLocation);
      map.add(marker);
      map.panBy(0, 1);
      amapRes = map;
    });
  };

  function handleMapLocation() {}
})();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

给钱,谢谢!

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

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

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

打赏作者

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

抵扣说明:

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

余额充值