当前位置:   article > 正文

天地图 uniapp使用笔记

天地图 uniapp使用笔记

官网地址:天地图API

效果:

  1. <template>
  2. <view>
  3. <!-- 显示地图的DOM节点 -->
  4. <view id="container" class="content"></view>
  5. <!-- END -->
  6. <!-- 数据显示 -->
  7. <h3>城市名称(IP属地):{{ city }}</h3>
  8. <h4>经纬度:{{ latitude }}</h4>
  9. <button @click="getCity()">获取用户定位</button>
  10. <!-- END -->
  11. </view>
  12. </template>
  13. <script>
  14. export default {
  15. data() {
  16. return {
  17. // 城市名称(IP属地)
  18. city: '',
  19. // 经纬度
  20. latitude: ''
  21. }
  22. },
  23. onLoad() {
  24. // 加载天地图插件
  25. this.loadMap()
  26. },
  27. methods: {
  28. /**
  29. * 加载天地图插件
  30. * @description 完毕后,可执行业务操作
  31. * @return void
  32. */
  33. loadMap() {
  34. try{
  35. // 您申请的天地图key
  36. const key = '您申请的Key,填写到此!'
  37. // 动态创建script标签引入
  38. var script = document.createElement("script");
  39. script.type = "text/javascript";
  40. script.src = "https://api.tianditu.gov.cn/api?v=4.0&tk=" + key;
  41. script.onload = script.onreadystatechange = () => {
  42. if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
  43. // 加载完毕,执行业务逻辑函数
  44. // ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  45. this.createMap();//创建地图
  46. // ....
  47. script.onload = script.onreadystatechange = null;
  48. }
  49. };
  50. document.body.appendChild(script);
  51. }catch(e){
  52. //TODO handle the exception
  53. }
  54. },
  55. /**
  56. * 创建地图
  57. * @description 匹配dom显示
  58. * @return void
  59. */
  60. createMap() {
  61. var map;
  62. var zoom = 12;
  63. map = new T.Map('container', {
  64. projection: 'EPSG:4326'
  65. })
  66. map.centerAndZoom(new T.LngLat(116.40769, 39.89945), zoom);
  67. },
  68. /**
  69. * 获取用户定位
  70. * @description IP属地/经纬度
  71. * @return void
  72. */
  73. getCity() {
  74. const lc = new T.LocalCity();
  75. lc.location((e) => {
  76. console.log(e)
  77. // 赋值data
  78. this.city = e.cityName;
  79. this.latitude = e.lnglat;
  80. })
  81. },
  82. }
  83. }
  84. </script>
  85. <style scoped>
  86. /* 自定义宽高等样式 */
  87. .content {
  88. height: 300px;
  89. width: 100%;
  90. }
  91. </style>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/741694
推荐阅读