如何再vue项目中使用cdn(以使用天地图得cdn获取当前位置为例)

  • 如何再vue项目中使用cdn(以使用天地图得cdn获取当前位置为例)已关闭评论
  • 93 次浏览
  • A+
所属分类:Web前端
摘要

http://lbs.tianditu.gov.cn/api/js4.0/examples.html
在其中可以了解天地图的基本使用教程


一、了解天地图

http://lbs.tianditu.gov.cn/api/js4.0/examples.html
在其中可以了解天地图的基本使用教程

但其中的教程均为h5引入cdn的方式
以h5定位为例来改成vue项目
源码:

<!DOCTYPE html> <html> <head>     <meta http-equiv="content-type" content="text/html; charset=utf-8"/>     <meta name="keywords" content="天地图"/>     <title>天地图-地图API-范例-H5定位</title>     <script type="text/javascript" src="http://api.tianditu.gov.cn/api?v=4.0&tk=您的密钥"></script>     <style type="text/css">body,html{width:100%;height:100%;margin:0;font-family:"Microsoft YaHei"}#mapDiv{width:100%;height:400px}input,b,p{margin-left:5px;font-size:14px}</style>     <script>         var map;         var zoom = 12;         function onLoad() {             //初始化地图对象             map = new T.Map("mapDiv");             //设置显示地图的中心点和级别             map.centerAndZoom(new T.LngLat(116.40969, 38.89945), zoom);             var lo = new T.Geolocation();             fn = function (e) {                 if (this.getStatus() == 0){                     map.centerAndZoom(e.lnglat, 15)                     alert("获取定位坐标:"+e.lnglat.lat + "," + e.lnglat.lng)                     var marker = new T.Marker(e.lnglat);                     map.addOverLay(marker);                  }                 if(this.getStatus() == 1){                     map.centerAndZoom(e.lnglat, e.level)                     alert("获取定位坐标:"+e.lnglat.lat + "," + e.lnglat.lng)                     var marker = new T.Marker(e.lnglat);                     map.addOverLay(marker);                 }             }             lo.getCurrentPosition(fn);         }     </script> </head> <body onLoad="onLoad()"> <div id="mapDiv"></div> <p>本示例演示如用H5定位所在城市</p> </body> </html> 

在入口index.html中加入cdn以达到全局效果

<!DOCTYPE html> <html lang="zh-cn">   <head>     <meta charset="UTF-8" />     <link rel="icon" href="/favicon.ico" />     <script type="text/javascript" src="http://api.tianditu.gov.cn/api?v=4.0&tk=****"></script>     <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0" />      <title>Mars3D三维地球APP</title>   </head>   <body>     <div id="app"></div>     <script type="module" src="/src/main.ts"></script>   </body> </html> 

然后在js文件中或者vue中就不需要再导入了,可以直接使用

/* eslint-disable */ // 通过经纬度获取详细地址 export default function getlocation(){     const lc = new T.LocalCity();     lc.location(function(e){         console.log(e)     }) }