微信小程序使用地图定位

一、效果展示

在这里插入图片描述

二、申请定位权限

使用微信小程序定位接口,必须申请这个权限,对类目也有要求,填写权限申请的时候,站在用户的角度填写通过率会高些。

在这里插入图片描述

在这里插入图片描述

三、申请腾讯地图sdk

申请流程地址:https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview

在这里插入图片描述

四、地图容器介绍

文档地址:https://developers.weixin.qq.com/miniprogram/dev/component/map.html
在这里插入图片描述

五、获取定位

文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.getLocation.html

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

六、源码

js代码

import util from "../../utils/util.js"

// 引入SDK核心类
var QQMapWX = require('../../utils/qqmap-wx');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
    
    
  key: '你申请的地图Key' // 必填
});

Page({
    
    
  data: {
    
    
    mapCtx: "",
    markers: [],
    poi: {
    
    },
    showLocation: false,
    coordType: '5',
    center_longitude: "",
    center_latitude: ""
  },
  //展示经纬度输入框
  showLocation() {
    
    
    this.setData({
    
     showLocation: true })
  },
  //隐藏经纬度输入框
  onCloseLocation() {
    
    
    this.setData({
    
     showLocation: false })
  },
  //坐标类型change
  coordOnChange(event) {
    
    
    this.setData({
    
    
      coordType: event.detail
    });
  },
  //坐标radio的click
  coordOnClick(event) {
    
    
    this.setData({
    
    
      coordType: event.currentTarget.dataset.name
    });
  },
  //表单提交
  formSubmit(e) {
    
    
    this.onCloseLocation()
    this.parseAddress(this.data.center_longitude, this.data.center_latitude, this.data.coordType)
  },
  /**地图点击事件*/
  mapChange(e) {
    
    
    let that = this
    console.log("change事件", e)
    that.parseAddress(e.detail.longitude, e.detail.latitude)
  },
  /**地图点击移动*/
  moveToLocation(longitude, latitude) {
    
    
    var that = this
    //this.parseAddress(longitude, latitude)
    this.mapCtx.moveToLocation({
    
    
      longitude: longitude,
      latitude: latitude,
      success(res) {
    
    
        console.log("移动成功", res)
      },
      fail(f) {
    
    
        console.log("移动失败", res)
      }
    })
  },
  /**重新定位*/
  moveToNow() {
    
    
    var that = this
    wx.getLocation({
    
    
      type: 'gcj02',
      success(res) {
    
    
        that.parseAddress(res.longitude, res.latitude)
      },
      fail(f) {
    
    
        console.log('获取经纬度失败', f)
        util.msg("n", "获取经纬度失败,请检查定位是否开启!")
      }
    })
  },
  /**第一次进入*/
  first(e) {
    
    
    var that = this
    wx.getLocation({
    
    
      type: 'gcj02',
      success(res) {
    
    
        that.parseAddress(res.longitude, res.latitude)
      },
      fail(f) {
    
    
        console.log('获取经纬度失败', f)
        util.msg("n", "获取经纬度失败,请检查定位是否开启!")
      }
    })
  },
  /**解析地址*/
  parseAddress(longitude, latitude, coordType = '5') {
    
    
    var _this = this
    qqmapsdk.reverseGeocoder({
    
    
      //位置坐标,默认获取当前位置,非必须参数
      location: {
    
    
        latitude: latitude,
        longitude: longitude
      },
      coord_type: coordType,
      success(res) {
    
    //成功后的回调
        console.log("解析成功", res);
        var res = res.result;
        var mks = [];
        //当get_poi为0时或者为不填默认值时,检索目标位置,按需使用
        mks.push({
    
     // 获取返回结果,放到mks数组中
          title: res.address,
          id: 0,
          latitude: res.location.lat,
          longitude: res.location.lng,
          iconPath: '../../images/icon/localtion.png',//图标路径 
          width: 30,
          height: 30,
          // callout: {
    
     //在markers上展示地址名称,根据需求是否需要
          //   content: res.address,
          //   color: '#000',
          //   display: 'ALWAYS'
          // }
        });
        _this.setData({
    
    
          markers: mks,
          poi: {
    
    
            latitude: res.location.lat,
            longitude: res.location.lng,
          }
        });
        _this.moveToLocation(res.location.lng, res.location.lat)
      },
      fail(error) {
    
    
        console.error('地址解析错误', error, longitude, latitude);
      }
    })
  },
  /**生命周期函数--监听页面加载*/
  onLoad(options) {
    
    
    this.mapCtx = wx.createMapContext('myMap')
    this.first()
  },
  /** 生命周期函数--监听页面隐藏*/
  onHide() {
    
    

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

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

  }
})

json

{
    
    
  "usingComponents": {
    
    
    "van-field": "/vant/field/index",
    "van-button": "/vant/button/index",
    "van-popup": "/vant/popup/index",
    "van-radio-group": "/vant/radio-group/index",
    "van-radio": "/vant/radio/index",
    "van-row": "/vant/row/index",
    "van-col": "/vant/col/index",
    "van-cell": "/vant/cell/index"
  },
  "navigationBarTitleText": "定位服务"
}

wxml

<view>
  <van-cell title="当前地址:{
    
    { markers[0].title }}" />
  <van-row>
    <van-col span="12">
      <van-cell title="经度:{
    
    { poi.longitude }}" />
    </van-col>
    <van-col span="12">
      <van-cell title="纬度:{
    
    { poi.latitude }}" />
    </van-col>
  </van-row>

  <view class="button_view">
    <van-button custom-class="submit_location" type="info" plain bind:click="moveToNow">重新定位</van-button>
    <van-button custom-class="submit_location" type="info" plain bind:click="showLocation">手动输入</van-button>
  </view>
</view>

<!-- 弹出层 -->
<van-popup custom-class="form_popup" show="{
    
    { showLocation }}" bind:close="onCloseLocation" round="true">
  <view class="form">
    <van-radio-group value="{
    
    { coordType }}" bind:change="coordOnChange">
      <van-row>
        <van-col span="12">
          <van-cell title="腾讯坐标" clickable data-name='5' bind:click="coordOnClick">
            <van-radio slot="right-icon" name='5' />
          </van-cell>
        </van-col>
        <van-col span="12">
          <van-cell title="GPS坐标" clickable data-name='1' bind:click="coordOnClick">
            <van-radio slot="right-icon" name='1' />
          </van-cell>
        </van-col>
      </van-row>
    </van-radio-group>

    <van-field type="digit" label="经度:" title-width="43px" model:value="{
    
    { center_longitude }}" clearable />
    <van-field type="digit" label="纬度:" title-width="43px" model:value="{
    
    { center_latitude }}" clearable />
    <view class="submit_button">
      <van-button custom-class="button" type="info" bindtap="formSubmit">提交</van-button>
    </view>
  </view>
</van-popup>

<!--地图容器-->
<!--longitude及latitude为设置为调转到指定坐标位置,默认不显示-->
<map class="map" id="myMap" markers="{
    
    {markers}}" longitude="{
    
    {poi.longitude}}" latitude="{
    
    {poi.latitude}}" scale='16' bindpoitap="mapChange" bindtap="mapChange" show-scale="true" show-compass="true" show-location="true">
</map>

wxss

.button_view {
    
    
  text-align: center;
  margin: 10px 0px 10px 0px;
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.submit_location {
    
    
  width: 150px;
}

.form_popup {
    
    
  width: 80%;
}

.form {
    
    
  margin: 10px;
}

.submit_button {
    
    
  margin-top: 10px;
  text-align: center;
}

.submit_button .button {
    
    
  height: 30px;
  width: 80%;
}

.map {
    
    
  position: absolute;
  top: 153px;
  width: 100%;
  height: 75%;
}

猜你喜欢

转载自blog.csdn.net/LuoHuaX/article/details/130412124