In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
I would like to share with you how to use the map in WeChat Mini Programs. I believe most people don't know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's learn about it together.
1. Prepare for
By reading the Tencent Map open platform, you can know that WeChat Mini Programs can download SDK to provide a direct call API to use Tencent Map. Of course, he can also encapsulate the request on URL and return his own data. This example is used because some APIs are called when encapsulated in SDK, and the same API is called in the example for a long time, which will result in frequent API call errors.
In the process, I will also use the vant of the likes team to display the school information, so I also need to install the dependent backup in advance. For specific installation steps, please see the official website.
two。 Actual combat
2.1 configure Mini Program permissions
The first thing is to allow users to enable location to our Mini Program when entering Mini Program. We need to add the following code to the app.json file:
"permission": {"scope.userLocation": {"desc": "your location information will be used for the effect display of Mini Program location interface"}}
With this field, when Mini Program uses the location system, it is found that if the permission of Mini Program is not given, it will allow the user to give the permission to Mini Program. The effect is as follows:
2.2 encapsulating tool functions
2.2.1 Global functions and variables
App.js
/ / Global variable globalData: {userInfo: null}, / / Global introduction method, easy introduction of third-party package require: ($url) = > require ($url) 2.2.2 tool function
Util.js
/ / introduce SDK core class const QQMapWX = require ('. / qqmap-wx-jssdk.min.js'); / / instantiate API core class let key =''; let qqmapsdk;key & (qqmapsdk = new QQMapWX ({key / / required})); module.exports = {qqmapsdk, key}
Here we introduce SDK and transfer the instantiated object directly, but here we need to give the Tencent map the open API key, which is not provided by my key. We send the key out because we need to use it later. In order not to expose our own key, the key is generally stored in the backend config during development, and here it is processed at the front end to facilitate the demonstration.
2.3 processing in front of the jump location page
To locate a mobile phone, not only Wechat permission is required, but also our mobile phone also has a location system permission to be enabled, so before we officially start positioning, we usually need a series of operations for users to better experience our function. Here I simply use button as a redirect.
Wxml
Go to use the map
First we need to add a click event to the button, where we can handle a lot of things; next let's take a look at the js code!
/ / introduce the required tool functions const app = getApp (); const {qqmapsdk} = app.require ('utils/util'); Page ({/ * Map start position * / / Click the button to jump to the map page gotoMap () {wx.showLoading ({title: "jumping to the map page"}) / / do several things to improve user experience before jumping / / 1. To verify that the user has enabled the location, boot / / 2 if not. You also need to verify the location permission of the program. If not, boot / / 3. Do the above two points before you can jump to wx.getLocation ({success (res) {wx.navigateTo ({url: "/ pages/map/index"})}, fail (e) {if (e & & (e.errCode = = 2 | | e.errCode = = 404)) {wx.showModal ({title: "prompt") Content: 'failed to get location information Please check whether the phone "location information" is not enabled', showCancel: false})} else if (e & & ((e.errMsg.indexOf ('getLocation:fail auth deny')! =-1) | | (e.errMsg.indexOf (' system permission denied')! =-1)) {showModal ({title: "prompt") Content: 'failed to get location information Please check whether Wechat has location permission', confirmText: "reacquire", success (res) {if (res.confirm = true) {detectSettings ()} else if (res.cancel = = true) {return })} else if (e.errMsg.indexOf ("frequent")! =-1) {wx.showModal ({title: "prompt", content: "the location information API is called too frequently. Please wait 10-30 seconds before you operate." , showCancel: false})}} Complete () {wx.hideLoading ()}) / / boot to enable Wechat location permission function detectSettings () {wx.getSetting ({success (res) {if (res & & (res.authSetting ["scope.userLocation"]! = = undefined & & res.authSetting ["scope.userLocation"]! = = true)) {wx.showModal ({ Title: "prompt" Content: "Mini Program does not have location permission Please go to set WeChat Mini Programs's location permission. " , confirmText: "go to setup" Success (res) {if (res.cancel = = true) {return} else if (res.confirm = true) {wx.openSetting ({success (result) {if (result & & (result.authSetting ["scope.userLocation"]! = = undefined & & result.authSetting ["scope.userLocation"] = true) {wx.navigateTo ({url: "/ pages/map/index"})} else {wx.navigateTo ({url: "/ pages) / index/index "})}} })}} Fail () {wx.navigateTo ({url: "/ pages/index/index"})})} else {wx.navigateTo ({url: "/ pages/map/index"})}} Complete () {wx.hideLoading ()})}))
After reading the code, let's take a look at the effect. Here we emphasize that the jump condition is not met. The effect is shown in GIF:
The above GIF does not deal with the mobile location system. This demo is relatively simple in this respect. It is gone at a hint. There are generally other better ways to deal with it in daily development. The effects of not turning on are as follows:
2.4 treatment after jump
2.4.1 Page initialization
After the processing in the previous step, we have confirmed that both permissions for the mobile phone have been given, so let's start processing the map location page and see what the finished product looks like before we start, as follows:
Wxml
Nearby schools {{city | | "Beijing"} {{count > 0? "drop-down refresh to get more information": "in the end"}} did not get the relevant data. no, no, no.
The overall framework is shown in the wxml above, and if all the data is provided, it will look like the figure above. Then let's go on to explain his logical implementation.
/ / introduce the required utility function const app = getApp (); const {qqmapsdk,key} = app.require ('utils/util'); / / initialize the lifecycle function onLoad: function (options) {_ this = this; _ this.init ()}
The following functions are not only used at load time, but will also be used later, which I distinguish with the parameters passed in. If it is called at load time, it is simply to get the user's current location, which is used for display; if an address is passed in, it will be used for address inverse resolution.
/ / resolve your address and get the current location init (location) {let query = {success (res) {console.log (res) if (res.status = 0) {/ / console.log (res.result.location) app.globalData.adInfo = res.result.ad_info _ this.setData ({city: res.result.ad_info.city, lat: res.result.location.lat, lng: res.result.location.lng,}) _ this.qqSearch ();} else {wx.showModal ({title: 'prompt', content:res.message | | "failed to get geolocation information." , showCancel: false}, fail (e) {console.log (e)}} location & & (query.location = location); qqmapsdk.reverseGeocoder (query) } 2.4.2 search function is implemented / / if you enter a city Only the city will be displayed, not the school searchSchool (e) {/ / not entered or a space if (e & & (! e.detail | | e.detail.trim () =')) {wx.showToast ({title: "Please enter a valid school name", icon: 'none', duration: 2000}) return} _ this.setData ({options: [] Count:-2}) _ this.qqSearch (e.detail) }, qqSearch (name) {/ / enter the school name wx.showLoading ({title: "getting information"}) const mks = []; let count, boundary= `nearby (${_ this.data.lat}, ${_ this.data.lng}, 1000) ` Search (name) function search (name) {const opts = {keyword: 'university', / / search keywords page_size: 15, page_index: _ this.data.pageIndex, / / get more key: key, boundary} If (name) {opts.boundary = `region (${_ this.data.city}) `opts.keyword = name} / / this is mainly to avoid errors caused by high-frequency calls to the API So you can only use URL to get the relevant information wx.request ({url: "https://apis.map.qq.com/ws/place/v1/search", method:" get ", data: {... opts}) Success: function (res) {/ / callback console.log (res) if after successful search (res.statusCode! = = 200 | | (res.data & & res.data.status! = = 0) return) / / initialization and other states / / calculation can be reduced several times to get more if (_ this.data.count =-1 | | _ this.data.count =-2) {count = res.data.count & & Math.floor (res.data.count/10);} else {count =-- _ this.data.count;} for (let I = 0; I)
< res.data.data.length; i++) { mks.push({ // 获取返回结果,放到mks数组中 title: res.data.data[i].title, address: res.data.data[i].address, }) } }, fail: function (e) { console.log(e) wx.showToast({ title: JSON.stringify(e) || "获取地图信息失败", icon: "none", duration: 3000 }) }, complete: function (){ setTimeout(()=>{wx.hideLoading () mks.push (. _ this.data.options); _ this.setData ({/ / set the markers property to display the search results in the map options: mks, count}), 1000)}) }}, 2.4.3 decline to get more / / decline to the end onReachBottom: function () {_ this.data.pageIndex = + _ this.data.pageIndex; _ this.data.count & & _ this.qqSearch ();}, 2.4.4 submit data
For the submission of data here do not do more processing, if you choose to remind, in the actual development generally need to store the data in the database for other purposes.
SubData (e) {const data = e.target.dataset.chooseopt; / / if (! data) return; wx.showModal ({title: "hint", content: `is your school [${data.title}]? `, success (res) {/ / cancel if (res.cancel) {return } else if (res.confirm) {/ / confirm / / request for addition or modification to the backend. A detailed address is generally required. Here we simply deal with wx.showToast ({title: data.title, icon: "none"})}}, fail () {wx.showToast ({title: "failure", icon: "error"})}} 2.4.5 switch city changeCity () {_ this.setData ({options: []) Count:-2, / / simple bidirectional data binding Enter and clear the contents of the input box schoolName:'}) wx.chooseLocation ({latitude:_this.data.lat, longitude:_this.data.lng, success (res) {if (res.errMsg = "chooseLocation:ok") {/ / get the selected location and parse the longitude and latitude _ this.init (`${res.latitude}, ${res.longitude}`) through address inverse parsing }}, / / Press the cancel button fail (e) {if (e.errMsg = "chooseLocation:fail cancel") {_ this.init ();}}, complete () {}})} above is all the content of the article "how to use Map in WeChat Mini Programs". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.