微信小程序 调用地图接口,实现定位

1. demo01.wxml

<!-- 定位 -->
<view>

  <button type="default" bindtap="get_location">get position</button>

</view>

<view>
  <map id="my_map" latitude="{
     
     {latitude}}" longitude="{
     
     {longitude}}" show-location="true" style="width: 400px"></map>
</view>

2. 配置app.json

{
    
    
  "pages": [
    "pages/demo01/demo01"
  ],
  "permission": {
    
    
    "scope.userLocation": {
    
    
      "desc": "你的位置信息将用于小程序位置接口的效果展示" 
    }
  }
}

3. demo01.js

// pages/demo01/demo01.js
Page({
    
    

  /**
   * 获取当前用户的经纬度  
   *  */
  data: {
    
    
    longitude: 0,
    latitude: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
    

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
    

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
    

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
    

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
    

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
    

  },
  get_location: function() {
    
    

    let temp_this = this;

    wx.getLocation({
    
    
      type: 'wgs84',
      success (res) {
    
    
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy

        temp_this.setData({
    
    
          latitude: latitude,
          longitude: longitude
        })

        let map_context = wx.createMapContext('my_map', temp_this);

        map_context.moveToLocation({
    
    longitude:longitude, latitude:latitude});
      }
     });

  

  } 
  
})

4. 测试

猜你喜欢

转载自blog.csdn.net/qq_44783283/article/details/110233426