Vue项目可以通用,不止再uniapp项目上

1. 创建uniapp 项目 或者 vue2 项目

2. index.html文件

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
  <!-- Open Graph data -->
  <!-- <meta property="og:title" content="Title Here" /> -->
  <!-- <meta property="og:url" content="http://www.example.com/" /> -->
  <!-- <meta property="og:image" content="http://example.com/image.jpg" /> -->
  <!-- <meta property="og:description" content="Description Here" /> -->
  <script>
    var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)'))
    document.write('<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + (coverSupport ? ', viewport-fit=cover' : '') + '" />')
  </script>
  <link rel="stylesheet" href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css" />
</head>
<body>
<noscript>
  <strong>Please enable JavaScript to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script type="text/javascript">
  var userAgent = navigator.userAgent;
  if (userAgent.indexOf('AlipayClient') > -1) {
    // 支付宝小程序的 JS-SDK 防止 404 需要动态加载,如果不需要兼容支付宝小程序,则无需引用此 JS 文件。
    document.writeln('<script src="https://appx/web-view.min.js"' + '>' + '<' + '/' + 'script>');
  } else if (/QQ/i.test(userAgent) && /miniProgram/i.test(userAgent)) {
    // QQ 小程序
    document.write(
            '<script type="text/javascript" src="https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"><\/script>'
    );
  } else if (/miniProgram/i.test(userAgent) && /micromessenger/i.test(userAgent)) {
    // 微信小程序 JS-SDK 如果不需要兼容微信小程序,则无需引用此 JS 文件。
    document.write('<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"><\/script>');
  } else if (/toutiaomicroapp/i.test(userAgent)) {
    // 头条小程序 JS-SDK 如果不需要兼容头条小程序,则无需引用此 JS 文件。
    document.write(
            '<script type="text/javascript" src="https://s3.pstatp.com/toutiao/tmajssdk/jssdk-1.0.1.js"><\/script>');
  } else if (/swan/i.test(userAgent)) {
    // 百度小程序 JS-SDK 如果不需要兼容百度小程序,则无需引用此 JS 文件。
    document.write(
            '<script type="text/javascript" src="https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.18.js"><\/script>'
    );
  } else if (/quickapp/i.test(userAgent)) {
    // quickapp
    document.write('<script type="text/javascript" src="https://quickapp/jssdk.webview.min.js"><\/script>');
  }
</script>
<script type="text/javascript" src="https://api.tianditu.gov.cn/api?v=4.0&tk={ak}"></script>

<!-- uni 的 SDK -->
<script type="text/javascript" src="<%= BASE_URL %>static/uni.webview.js"></script>
<script type="text/javascript">
  // 待触发 `UniAppJSBridgeReady` 事件后,即可调用 uni 的 API。
  document.addEventListener('UniAppJSBridgeReady', function() {
    console.log('UniAppJSBridgeReady');
    webUni.getEnv(function(res) {
      console.log('当前环境:' + JSON.stringify(res));
    });
  });
</script>
</body>
</html>

3. static/uni.webview.js 该文件,可在微信小程序中打开,

uniapp编译的h5页面操作,

1. 在h5页面中给uniapp发送消息通信

2. 跳转uniapp中的组件

! function (e, n) {
  "object" == typeof exports && "undefined" != typeof module ? module.exports = n() : "function" == typeof define && define.amd ? define(n) : (e = e || self).webUni = n()
}(this, (function () {
  "use strict";
  try {
    var e = {};
    Object.defineProperty(e, "passive", {
      get: function () {
        !0
      }
    }), window.addEventListener("test-passive", null, e)
  } catch (e) {}
  var n = Object.prototype.hasOwnProperty;

  function t(e, t) {
    return n.call(e, t)
  }
  var i = [],
    a = function (e, n) {
      var t = {
        options: {
          timestamp: +new Date
        },
        name: e,
        arg: n
      };
      if (window.__dcloud_weex_postMessage || window.__dcloud_weex_) {
        if ("postMessage" === e) {
          var a = {
            data: [n]
          };
          return window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessage(a) : window.__dcloud_weex_.postMessage(JSON.stringify(a))
        }
        var o = {
          type: "WEB_INVOKE_APPSERVICE",
          args: {
            data: t,
            webviewIds: i
          }
        };
        window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessageToService(o) : window.__dcloud_weex_.postMessageToService(JSON.stringify(o))
      }
      if (!window.plus) return window.parent.postMessage({
        type: "WEB_INVOKE_APPSERVICE",
        data: t,
        pageId: ""
      }, "*");
      if (0 === i.length) {
        var r = plus.webview.currentWebview();
        if (!r) throw new Error("plus.webview.currentWebview() is undefined");
        var d = r.parent(),
          s = "";
        s = d ? d.id : r.id, i.push(s)
      }
      if (plus.webview.getWebviewById("__uniapp__service")) plus.webview.postMessageToUniNView({
        type: "WEB_INVOKE_APPSERVICE",
        args: {
          data: t,
          webviewIds: i
        }
      }, "__uniapp__service");
      else {
        var w = JSON.stringify(t);
        plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE", '",').concat(w, ",").concat(JSON.stringify(i), ");"))
      }
    },
    o = {
      navigateTo: function () {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
          n = e.url;
        a("navigateTo", {
          url: encodeURI(n)
        })
      },
      navigateBack: function () {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
          n = e.delta;
        a("navigateBack", {
          delta: parseInt(n) || 1
        })
      },
      switchTab: function () {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
          n = e.url;
        a("switchTab", {
          url: encodeURI(n)
        })
      },
      reLaunch: function () {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
          n = e.url;
        a("reLaunch", {
          url: encodeURI(n)
        })
      },
      redirectTo: function () {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
          n = e.url;
        a("redirectTo", {
          url: encodeURI(n)
        })
      },
      getEnv: function (e) {
        window.plus ? e({
          plus: !0
        }) : e({
          h5: !0
        })
      },
      postMessage: function () {
        var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
        a("postMessage", e.data || {})
      }
    },
    r = /uni-app/i.test(navigator.userAgent),
    d = /Html5Plus/i.test(navigator.userAgent),
    s = /complete|loaded|interactive/;
  var w = window.my && navigator.userAgent.indexOf("AlipayClient") > -1;
  var u = window.swan && window.swan.webView && /swan/i.test(navigator.userAgent);
  var c = window.qq && window.qq.miniProgram && /QQ/i.test(navigator.userAgent) && /miniProgram/i.test(navigator.userAgent);
  var g = window.tt && window.tt.miniProgram && /toutiaomicroapp/i.test(navigator.userAgent);
  var v = window.wx && window.wx.miniProgram && /micromessenger/i.test(navigator.userAgent) && /miniProgram/i.test(navigator.userAgent);
  var p = window.qa && /quickapp/i.test(navigator.userAgent);
  for (var l, _ = function () {
      window.UniAppJSBridge = !0, document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady", {
        bubbles: !0,
        cancelable: !0
      }))
    }, f = [function (e) {
      if (r || d) return window.__dcloud_weex_postMessage || window.__dcloud_weex_ ? document.addEventListener("DOMContentLoaded", e) : window.plus && s.test(document.readyState) ? setTimeout(e, 0) : document.addEventListener("plusready", e), o
    }, function (e) {
      if (v) return window.WeixinJSBridge && window.WeixinJSBridge.invoke ? setTimeout(e, 0) : document.addEventListener("WeixinJSBridgeReady", e), window.wx.miniProgram
    }, function (e) {
      if (c) return window.QQJSBridge && window.QQJSBridge.invoke ? setTimeout(e, 0) : document.addEventListener("QQJSBridgeReady", e), window.qq.miniProgram
    }, function (e) {
      if (w) {
        document.addEventListener("DOMContentLoaded", e);
        var n = window.my;
        return {
          navigateTo: n.navigateTo,
          navigateBack: n.navigateBack,
          switchTab: n.switchTab,
          reLaunch: n.reLaunch,
          redirectTo: n.redirectTo,
          postMessage: n.postMessage,
          getEnv: n.getEnv
        }
      }
    }, function (e) {
      if (u) return document.addEventListener("DOMContentLoaded", e), window.swan.webView
    }, function (e) {
      if (g) return document.addEventListener("DOMContentLoaded", e), window.tt.miniProgram
    }, function (e) {
      if (p) {
        window.QaJSBridge && window.QaJSBridge.invoke ? setTimeout(e, 0) : document.addEventListener("QaJSBridgeReady", e);
        var n = window.qa;
        return {
          navigateTo: n.navigateTo,
          navigateBack: n.navigateBack,
          switchTab: n.switchTab,
          reLaunch: n.reLaunch,
          redirectTo: n.redirectTo,
          postMessage: n.postMessage,
          getEnv: n.getEnv
        }
      }
    }, function (e) {
      return document.addEventListener("DOMContentLoaded", e), o
    }], m = 0; m < f.length && !(l = f[m](_)); m++);
  l || (l = {});
  var E = "undefined" != typeof webUni ? webUni : {};
  if (!E.navigateTo)
    for (var b in l) t(l, b) && (E[b] = l[b]);
  return E.webView = l, E
}));

4. vue 代码

<template>
  <view class="uni-padding-wrap uni-common-mt">
    <div id="map"></div>
    <text type="primary" @click="start()">开 启</text>
    <button type="primary" @click="stop()">关 闭</button>
    <button type="primary" @click="save()">保存</button>
    <button type="primary" @click="enableEdit()">编辑</button>
    <button type="primary" @click="disableEdit()">禁止编辑</button>
    <button type="primary" @click="query()">查询</button>

    <button type="primary" @click="polygonTool.open()">开启</button>
    <button type="primary" @click="polygonTool.close()">关闭</button>
    <button type="primary" @click="getMapCenter()">获取地图中心点坐标</button>
    <button type="primary" @click="skip()">跳转</button>
  </view>

  <!--  <div>-->

  <!--  </div>-->
</template>

<script>
import webUni from '@/static/uni.webview.js';

export default {
  name: "map2",
  data() {
    return {
      map: {},//地图
      infoWin: '',
      lineTool: '',//测距工具
      polygonTool: '',//测面工具
      cp: '',
      marker: '',
      points: [],
      lineList: [],
      markerList: [],
      polygon: '',
    };
  },
  mounted() {
    document.addEventListener('UniAppJSBridgeReady', () => {
      alert(webUni)
    });
    this.load();


    // let script = document.createElement('script')
    // script.type = 'text/javascript'
    // script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=b021471cd63f5988daf8488bcdaf4bd9'
    // document.body.appendChild(script)
  },

  onLoad() {
  },

  methods: {
    skip() {
      webUni.postMessage({
        data: {
          info: {
            name: 'wft',
            age: 18
          }
        }
      })
      webUni.navigateTo({
        url: '/pages/userList/userList'
      });
    },
    //优化地图初始化,解决切换重新绘画
    load() {
      var T = window.T;
      const imageURL = "http://t0.tianditu.gov.cn/img_w/wmts?" +
          "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
          "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
          "&tk={ak}";//卫星图影像
      var lay = new T.TileLayer(imageURL, {minZoom: 1, maxZoom: 18});
      var config = {layers: [lay], name: 'TMAP_SATELLITE_MAP'};

      this.map = new T.Map('map', config); // 地图实例

      // var ctrl = new T.Control.MapType([{
      //   title: "卫星混合",
      //   icon: "http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellitepoi.png",
      //   layer: TMAP_HYBRID_MAP
      // }, {
      //   title: "地图",//地图控件上所要显示的图层名称
      //   icon: "http://api.tianditu.gov.cn/v4.0/image /map/maptype/vector.png",
      //   layer: TMAP_NORMAL_MAP//地图类型对象,即MapType。
      // }])
      // this.map.addControl(ctrl);
      // 设置地图位地星混合图层
      this.map.setMapType(window.TMAP_HYBRID_MAP);

      this.map.centerAndZoom(new T.LngLat(128.36225, 45.46233), 15);
      //允许鼠标双击放大地图
      this.map.enableScrollWheelZoom();
      this.map.enableDrag();
      //创建比例尺控件对象 添加比例尺控件
      var scale = new T.Control.Scale();
      this.map.addControl(scale);

      var config = {
        showLabel: true,
        color: "red", weight: 3, opacity: 0.5, fillColor: "#FFFFFF", fillOpacity: 0.5
      };
      //创建标注工具对象
      this.lineTool = new T.PolylineTool(this.map, config);
      //创建标注工具对象
      this.polygonTool = new T.PolygonTool(this.map, config);

      this.cp = new T.CoordinatePickup(this.map, {callback: this.getLngLat})
    },

    /**
     * 标注,连线
     * @param e
     */
    getLngLat(e) {
      console.log("经纬度点:", e)
      this.points.push(new T.LngLat(e.lng, e.lat))
      console.log("points", this.points)
      // 计算距离
      console.log("距离:", this.lineTool.getDistance(this.points))
      // 线重复 覆盖,移除上一个线,再覆盖新的线
      if (this.points.length > 1) {
        // 移除上一条线
        this.map.removeOverLay(this.lineList[this.lineList.length - 1]);
      }
      // 向地图上添加线
      var line = new T.Polyline(this.points);
      this.map.addOverLay(line);
      this.lineList.push(line);

      // 向地图上添加标注
      this.marker = new T.Marker(new T.LngLat(e.lng, e.lat));
      this.map.addOverLay(this.marker);
      // 启用拖拽
      this.marker.enableDragging();

      // dragstart	{type,target }	当用户拖动标注图标时触发。
      // drag	{type,target,lnglat }	当用户拖动标注图标时不断触发。
      // dragend	{type,target,lnglat }	当用户停止拖动标注图标时触发。
      // remove	{type,target }	移除标注图标时触发。
      // 记录拖拽起始点,用于拖拽结束时,更新线的坐标
      var tempLng;
      var tempLat;
      this.marker.addEventListener("dragstart", function (e) {
        tempLng = e.target.or.lng;
        tempLat = e.target.or.lat;

      })
      // 实现拖拽标注时,形成的线也跟着移动
      this.marker.addEventListener("dragend", function (e) {
        console.log(this.points)
        for (let i = 0; i < this.points.length; i++) {
          if (this.points[i].lng == tempLng && this.points[i].lat == tempLat) {
            this.points[i].lng = e.lnglat.lng;
            this.points[i].lat = e.lnglat.lat;
            break;
          }
        }
        line.setLngLats(this.points);
      })
    },

    /**
     * 放置点标注
     * @param lng 经度
     * @param lat 纬度
     * 存入points数组
     * 添加线、添加标注
     * 启动标注拖拽
     */
    save() {
      this.markerList.forEach(function (item) {
        this.map.removeOverLay(item);
        this.marker.disableDragging();
      })
      // 移除点击标注
      this.cp.removeEvent();
      // if (polygon != null) {
      //     map.clearOverLays();
      //     points = polygon.getLngLats()[0];
      //     console.log("新的多边形点:", points)
      //     polygon = null;
      // }
      this.putMapPolygon(this.points);
    },

    /**
     * 放置多边形
     * @param points 点数组
     */
    putMapPolygon(points) {
      var polygon = new T.Polygon(points, {
        color: "blue",
        weight: 3,
        opacity: 0.5,
        fillColor: "#FFFFFF",
        fillOpacity: 0.5
      });
      this.map.addOverLay(polygon);
      // this.polygonList.push(polygon);
      console.log("多边形边界:", polygon.getBounds())
      console.log("多边形面积-> ", this.polygonTool.getArea(points))
      //向地图上添加面
      var markerInfoWin = new T.InfoWindow("多边形面积:" + this.polygonTool.getArea(points) + "㎡  \n" + this.polygonTool.getArea(points) * (15 / 10000) + "亩");
      // 将标注添加到地图中
      polygon.addEventListener("click", function () {
        polygon.openInfoWindow(markerInfoWin);
      });
    },

    /**
     * 启用标注
     */
    start() {
      this.cp.addEvent();
    },

    /**
     * 停用标注
     */
    stop() {
      this.cp.removeEvent();
    },

    /**
     * 启用多变形编辑
     * 停用点击标注
     */
    enableEdit() {
      this.polygon.enableEdit();
      this.cp.removeEvent();
    },

    /**
     * 停止编辑后
     * 禁用点击标注
     * 根据新的经纬度数组重新构建多边形地块
     */
    disableEdit() {
      this.polygon.disableEdit();
      this.cp.removeEvent();
      buildPolygon();
    },

    /**
     *  清除原有点、线
     *  将新的点、线、多边形绘制
     */
    buildPolygon() {
      this.map.clearOverLays();
      console.log("新的多边形点:", this.polygon.getLngLats()[0])
      this.putMapPolygon(this.polygon.getLngLats()[0]);

      // for (let i = 0; i < polygon.getLngLats()[0].length; i++) {
      //     marker = new T.Marker(polygon.getLngLats()[0][i]);
      //     //向地图上添加标注
      //     map.addOverLay(marker);
      //     // // 启用拖拽
      //     // marker.enableDragging();
      // }
    },
    /**
     * 获取当前地图中心点
     */
    getMapCenter() {
      alert("当前地图中心点:" + this.map.getCenter().getLng() + "," + this.map.getCenter().getLat());
    },

  },
}
</script>

<style lang='less' scoped>
#map {
  position: relative;
  width: 100%;
  height: 500px;
  overflow: hidden;
  z-index: 3;
}
</style>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐