Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of location in Html5

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to solve the positioning problem in Html5. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Goal and analysis

Our goal is that after encapsulation, we only need to call a method to get the returned location information.

What we need to do is to encapsulate different classes for different sides (Wechat H5 and other browser environments), then distinguish them by a method through UA, and call the classes corresponding to different environments to get the location.

Within Wechat, after repeated practice, whether it is through the native HTML5 positioning, or through a third party (such as Baidu or Tencent Map) jsapi to obtain the location, not only a long positioning time, and even often positioning failure occurs, seriously affecting the user experience, especially for the mall home page where most of the information flow depends on the location, which is completely unacceptable. So in Wechat, we only have Wechat sdk.

For the browser side, the location information can be obtained stably and quickly through the third-party map jsapi or location component. In order to be consistent with Wechat as much as possible, we choose Tencent Map jsapi.

Solution

Talk is cheap, show me the code. Don't say much nonsense, just go to the code:

1. In the browser, get the location through Tencent Map jsapi

1.1 introduce Tencent Map jsapi into the html template file of the project:

Description:

To use Tencent Map jsapi, you need to go to Tencent Map open platform to apply for your own account, and then create your own application to replace the above value with Tencent Map key and the name of the application you created.

1.2 call the API to get location to obtain location information

To facilitate reuse, we separately encapsulate a class of Tencent Map jsapi, named tMap.js

/ / tMap.jsconst qq = window.qqvar geolocation = nullif (qq & & qq.maps) {/ / initialize positioning component geolocation = new qq.maps.Geolocation ('QVLBZ-YUULR-OUMW7-WKXFD-4SUWS-UDBIA',' mymap')} class TMap {/ / get the cumulative number of positioning counters that failed to locate more than 3 times and then do not continue Throw location failure error getPositionCount = 0 / / the exposed API getLocation () {return new Promise ((resolve, reject) = > {/ / callback this.getTMapLocation (resolve, reject)})} / / call Tencent Map to get the location getTMapLocation (success) Fail) {const _ self = this / / callback const showPosition = position = > {uni.setStorage ({key: 'positionData') Data: position}) success (position)} / / location failure callback const showErr = (err) = > / / if you fail to get the location more than 3 times, throw an error or continue to obtain the location information if (this.getPositionCount > 3) {fail ('more than 3 times failed to get the location')} else {/ / location failed recursive _ self.getPositionCount = _ self.getPositionCount + 1 _ self.getTMapLocation (success Fail)}} / / call Tencent web location component to obtain location information if (geolocation) {geolocation.getIpLocation (showPosition, showErr, {timeout: 6000, / / location timeout unit ms failTipFlag: true})}} export default new TMap ()

two。 In Wechat webview, obtain location information through Wechat sdk

2.1 preparation work related to Wechat js-sdk

2.1.1 introduction of js files

/ * * Wechat sdk asynchronous load * @ param {*} src * @ param {*} callback api interface * / export const handlerLoadScript = callback = > {const src= `https://res.wx.qq.com/open/js/jweixin-1.4.0.js` if (! (typeof callback = 'function')) {callback = function () {}} var check = document.querySelectorAll (`script [src= "${src}"] `) if (check.length > 0) {check [0] .addEventListener ('load' Function () {callback ()} callback () return} var script = document.createElement ('script') var head = document.getElementsByTagName (' head') [0] script.type = 'text/javascript' script.charset =' UTF-8' script.src = src if (script.addEventListener) {script.addEventListener ('load', function () {callback ()} False)} else if (script.attachEvent) {script.attachEvent ('onreadystatechange', function () {var target = window.event.srcElement if (target.readyState =' loaded') {callback ()})} head.appendChild (script)}

2.1.2 injection permission verification configuration

All pages that need to use JS-SDK must first inject configuration information, otherwise it will not be called. Configuration information is usually obtained through the background interface.

/ * injection permission verification configuration * @ param {object} Wechat js-sdk permission verification configuration * / export const wxconfigInfo = config = > {wx.config ({debug: false, / / enable debug mode, the returned values of all api called will be alert on the client side. To view the passed parameters, you can open them on the PC side, and the parameter information will be typed out through log and printed only on the PC side. AppId: config.appId, timestamp: parseInt (config.timestamp), nonceStr: config.nonceStr, signature: config.signature, jsApiList: [/ / list of jsapi to be used..., 'getLocation' / / get geographic location]})}

2.2 call api to get location information

/ * Wechat get position * / export const handleGetLocation = (config) = > {return new Promise ((resolve, reject) = > {wxconfigInfo (config) wx.ready (function () {wx.getLocation ({type: 'wgs84', / / defaults to the gps coordinates of wgs84). If you want to return the Mars coordinates directly to openLocation Input 'gcj02' success: function (res) {console.warn (' Wechat sdk successfully located', res) resolve ({lat: res.latitude, / / Latitude lng: res.longitude, / / Longitude speed: res.speed, / / Speed In meters per second, accuracy: res.accuracy / / position accuracy}}, fail: function (err) {console.error ('Wechat sdk location failure', err) reject (err)})}) wx.error (function (err) {/ / config Information Verification failure executes error function If the verification fails due to the expiration of the signature, you can view the error message in the debug mode of config or in the returned res parameter. For SPA, you can update the signature here. Console.log ('wxjsapi-error=', err) reject (`wxjsapi-error: ${err} `)})

2.3 call different location methods according to different operating environments

/ / public.js/** * UA enumeration * / const UA = {/ * Wechat H6 * / WECHAT: 'WECHAT', / * Alipay H6 * / ALIPAY:' ALIPAY' / * other * / OTHERS: 'OTHERS'} / * determine the running environment of the client. Here, only Wechat and browser h6 * / export const getUserAgent = () = > {var userAgent = navigator.userAgent.toLowerCase () if (userAgent.match (/ Alipay/i) = =' alipay') {return UA.ALIPAY} else if (userAgent.match (/ MicroMessenger/i) = = 'micromessenger') {return UA.WECHAT} else {return UA.OTHERS}} / / js-sdk.js/** * evoke Wechat api * @ param {*} _ href current page url * @ param {*} options sharing information * @ param {*} apiType call api type * / export const handleWXSDKCall = (_ href ApiType, options) = > {return new Promise ((resolve) Reject) = > {/ / get configuration information WeChatServivce.sign (_ href) .then (res = > {if (res) {if (apiType = 'location') {handleGetLocation (res). Then ((res) = > {resolve (res)}) .catch (err= > {reject (err)) Catch (err = > {reject (`catch: ${err} `) uni.showToast ({title: err.data.code + err.data.msg) Mask: true, icon: 'none'})})} / / getLocation.jsimport {getUserAgent HandlerLoadScript} from'@ / module/utils'import {handleWXSDKCall} from'@ / module/utils/wechat/wxJsApiSdk'import UA from'@ / module/enums/userAgent'import TMap from'@ / module/utils/tMap'/** * method for obtaining the location of external exposure * @ return Promise resolve A positionData object lat- latitude lng- longitude * / const getLocation = () = > {return new Promise ((resolve) Reject) = > {console.log ('enter the global method to obtain the user's location') const storageData = uni.getStorageSync ('positionData') const userAgent = getUserAgent () if (storageData) {resolve (storageData)} else {/ / based on the environment, if you use Wechat sdk in Wechat other use Tencent Map positioning component if (userAgent = = UA.WECHAT) {handlerLoadScript (() = > {handleWXSDKCall_ (window.location.href 'location') .then ((res) = > {uni.setStorageSync (' positionData', res) resolve (res)}) .catch (err = > {reject (err)} else {TMap.getLocation () .then (res = > {uni.setStorageSync ('positionData')) Res) resolve (res)}) .catch ((err) = > {reject (err)})} export default getLocation

3. Page call

3.1 bind the method to the Vue prototype:

Import getLocation from'@ / module/utils/getLocation'Vue.prototype.$getLocation = getLocation

3.2 call in the page component:

OnShow () {/ / request the background interface this.$getLocation () .then (res = > {console.warn ('home page acquisition location successful', res) this.latitude = res.lat this.longitude = res.lng / / here request the background interface based on the latitude and longitude obtained.}) .catch (err = > {console.error ('home page acquisition location failed') Err) / / error handling})}

Summary

The pit encountered and the points to pay attention to:

To obtain location information using Wechat sdk, you need to complete the following steps in order:

Asynchronously load Wechat sdk

Obtain configuration information through the API and configure Wechat sdk

Call method in wx.ready callback

The above three steps must be completed in strict order, otherwise the function of Wechat sdk cannot be called.

Thank you for reading! This is the end of the article on "how to solve the positioning problem in Html5". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report