加载中…

地图Demo

# 前言 本教程是基于 “apifm-wxapi” 模块,教你快速实现小程序开发,所以你可能需要先了解以下知识点: [《创建 HelloWorld 项目》](https://www.yuque.com/apifm/doc/hezlrm) [《使用 “apifm-wxapi” 快速开发小程序》](https://www.yuque.com/apifm/doc/mdldsd) # 功能说明 1. 知道坐标,可以查询该坐标的地址 2. 给定两个坐标,可以计算两点之间的距离(公里 / km) # 特别说明 本案例中,使用到了微信小程序的2个官方接口: ```plain wx.getLocation() wx.chooseLocation() ``` _为了保护用户隐私,微信有规定,必须要告诉用户使用定位的业务用途,以便帮助用户决策是否要允许小程序读取 TA 的定位信息:_ [https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#permission](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#permission) 所以,根据微信小程序官方的说明,本案例在 app.json 文件中加入了使用场景说明: ```plain "permission": { "scope.userLocation": { "desc": "微信规定必须要说明定位用途" } } ``` ## wxml代码 ```plain ``` ## js代码 ```plain const WXAPI = require('apifm-wxapi') Page({ data: { latitude: undefined, longitude: undefined }, onLoad: function (options) { }, onShow: function () { }, queryAddress(){ // 读取当前定位坐标 const _this = this wx.getLocation({ type: 'wgs84', success(res) { console.log(res) _this.setData(res) _this.mapQQAddress(res) } }) }, mapQQAddress(e){ // 坐标查地址 const location = e.latitude + ',' + e.longitude WXAPI.mapQQAddress(location, 1).then(res => { console.log('地址查看:', res) if (res.code == 0) { wx.showModal({ title: '成功', content: res.data.result.address, showCancel: false }) } }) }, selAddress(){ // 选择一个地址,读取坐标后计算距离 const _this = this if (!this.data.latitude || !this.data.longitude) { wx.showToast({ title: '请先读取当前地址', icon: 'none' }) return } wx.chooseLocation({ success: (e) => { console.log(e) WXAPI.mapDistance(_this.data.latitude, _this.data.longitude, e.latitude, e.longitude).then(res => { console.log(res) if (res.code == 0) { wx.showModal({ title: '成功', content: '距离:' + res.data + '公里', showCancel: false }) } }) } }) } }) ``` # 总结 本案例主要使用了 apifm-wxapi 的以下方法: ```plain WXAPI.mapDistance(lat1, lng1, lat2, lng2) WXAPI.mapQQAddress(location, coord_type) ``` > coord_type 参数: > > 1 GPS坐标 2 sogou经纬度 3 baidu经纬度 4 mapbar经纬度 5 [默认]腾讯、google、高德坐标 6 sogou墨卡托 > _关于  apifm-wxapi 更多的使用方法:_ [《apifm-wxapi使用说明》](https://github.com/gooking/apifm-wxapi/blob/master/instructions.md) _本案例Demo代码下载:_ [《apifm-wxapi使用Demo程序》](https://github.com/gooking/apifm-wxapi-demo) 期待你的进步! 感谢!