微信小程序中使用騰訊地圖,導航到目的地

1.效果圖如下:(點擊地圖可導航,從用戶當前位置到目的地)

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

2. wxml文件中
(1)目標地址location

在這裏插入圖片描述

<!-- 地址 -->
<view class='loc'>
  <view>
    <text class='iconfont icon-location'></text>
  </view>
  <view class='location'>{{location}}</view>
</view>
(2)地圖map

在這裏插入圖片描述

<!-- 地圖 -->
<view class='maps'>
  <view class="page-section page-section-gap">
    <map
      id="myMap"
      style="width: 100%; height: 100%; border-radius: 20px;"
      latitude="{{latitude}}"
      longitude="{{longitude}}"
      markers="{{markers}}"
      bindtap="getLoc"
      show-location
    ></map>
  </view>
</view>
3. js文件中
(1)前提是已經申請了騰訊地圖的密鑰,下載js放在utils文件中,在js文件中引入

在這裏插入圖片描述

var app = getApp();
// 引入SDK核心類
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
// 實例化API核心類
var qqmapsdk;
(2)頁面的初始數據,包括地址location,緯度latitude,經度longitude和圖標定位markers

在這裏插入圖片描述

Page({
  data: {
    phone: "",
    location: "",
    latitude: "",
    longitude: "",
    // 圖標定位
    markers: [],
  },
(3)wx.request請求後臺數據,包括location,latitude,longitude,返回的經緯度也賦給markers數組(定位圖標所需)

在這裏插入圖片描述
在這裏插入圖片描述

// 數據加載
  onLoad: function (options) {
    var that = this;
    // 發送請求,GET
    // 成功後臺返回location,latitude,longitude
    wx.request({
      url: 'https://XXXXXX?userId=' + app.id,
      method: 'GET',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        that.setData({
          // 地址+經緯度
          location: res.data.data.address,
          latitude: res.data.data.lat,
          longitude: res.data.data.lng,
          // 電話
          phone: res.data.data.phone,
          // 定位標誌的經緯度
          markers: [{
            latitude: res.data.data.lat,
            longitude: res.data.data.lng,
          }]
        });
      },
      fail: function (res) {
        console.log('失敗了');
      }
    });
  },
(4)點擊地圖,先調用wx.getLocation獲取當前用戶的經緯度(導航所需),成功之後,再調用wx.openLocation打開地圖

在這裏插入圖片描述

// 地圖
  onReady: function (e) {
    this.mapCtx = wx.createMapContext('myMap')
  },
// 地圖導航
  getLoc: function (e) {
    // console.log(e.currentTarget.id);  // 獲取當前點擊的數組下標
    var that = this;
    wx.getLocation({
      type: 'gcj02', // 默認爲wgs84的gps座標,如果要返回直接給openLocation用的火星座標,可傳入'gcj02'
      success: function (res) {
        //使用微信內置地圖查看位置接口
        wx.openLocation({
          latitude: parseFloat(that.data.latitude),  // 要去的地址經度,浮點數
          longitude: parseFloat(that.data.longitude),  // 要去的地址緯度,浮點數
          name: '終點位置',  // 位置名
          address: that.data.location,  // 要去的地址詳情說明
          scale: 18,   // 地圖縮放級別,整形值,範圍從1~28。默認爲最大
          infoUrl: 'http://www.gongjuji.net'  // 在查看位置界面底部顯示的超鏈接,可點擊跳轉(測試好像不可用)
        });
      },
      cancel: function (res) {
        console.log('地圖定位失敗');
      }
    })
  },

希望對你有幫助,若有疑問可留言討論,謝謝~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章