Skip to content

Commit

Permalink
Merge pull request #190 from xiaoyan428820/release-3.6.8-app
Browse files Browse the repository at this point in the history
fix: 位置模块接口实现问题及样例修改
  • Loading branch information
szzwk authored Sep 8, 2023
2 parents fd469ee + 9abbc97 commit 5ac211c
Show file tree
Hide file tree
Showing 8 changed files with 379 additions and 64 deletions.
79 changes: 76 additions & 3 deletions examples/mini-program-example/src/pages/api/location/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,16 @@ export default class Index extends React.Component {
},
{
id: 'getLocation',
func: (apiIndex) => {
inputData: {
altitude: "false",
highAccuracyExpireTime: 8000,
isHighAccuracy: true,
type: 'wgs84',
},
func: (apiIndex, data) => {
TestConsole.consoleTest('getLocation')
Taro.getLocation({
...data,
success: (res) => {
this.setState({
location: this.formatLocation(res.longitude, res.latitude),
Expand All @@ -128,11 +135,22 @@ export default class Index extends React.Component {
{
id: 'chooseLocation',
inputData: {
latitude: 45,
longitude: 89,
mapOpts: {
type: 1,
search: 1,
coord: [39.90374, 116.397827],
// coordtype: 5,
policy: 0,
mapdraggable: 1,
zoom: 15,
radius: 1000,
total: 10,
referer: 'myTaro'
},
},
func: (apiIndex, data) => {
try {
TestConsole.consoleTest('chooseLocation')
// 需要配置全局变量LOCATION_APIKEY
Taro.chooseLocation({
...data,
Expand All @@ -153,6 +171,61 @@ export default class Index extends React.Component {
}
},
},
{
id: 'getFuzzyLocation',
inputData: {
type: 'gcj02',
},
func: (apiIndex, data) => {
try {
TestConsole.consoleTest('getFuzzyLocation')
Taro.getFuzzyLocation({
...data,
success: (res) => {
TestConsole.consoleSuccess.call(this, res, apiIndex)
},
fail: (res) => {
TestConsole.consoleFail.call(this, res, apiIndex)
},
complete: (res) => {
TestConsole.consoleComplete.call(this, res, apiIndex)
},
}).then((res) => {
TestConsole.consoleReturn.call(this, res, apiIndex)
})
} catch (err) {
TestConsole.consoleDebug('getFuzzyLocation', err)
}
},
},
{
id: 'openLocation',
func: async (apiIndex) => {
try {
TestConsole.consoleTest('openLocation')
const loc = await Taro.getFuzzyLocation({type: 'gcj02'})
Taro.openLocation({
longitude: loc.longitude,
latitude: loc.latitude,
name: '未来科技城',
address: '中国湖北省武汉市高新大道999号未来科技城',
success: (res) => {
TestConsole.consoleSuccess.call(this, res, apiIndex)
},
fail: (res) => {
TestConsole.consoleFail.call(this, res, apiIndex)
},
complete: (res) => {
TestConsole.consoleComplete.call(this, res, apiIndex)
},
}).then((res) => {
TestConsole.consoleReturn.call(this, res, apiIndex)
})
} catch (err) {
TestConsole.consoleDebug('openLocation', err)
}
},
},
],
}
formatLocation(longitude, latitude) {
Expand Down
41 changes: 12 additions & 29 deletions packages/taro-mpharmony/src/api/location/chooseLocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,25 @@ import { stringify } from 'query-string'
import { MethodHandler } from '../../utils/handler'

let container: HTMLDivElement | null = null
function createLocationChooser (handler, key = LOCATION_APIKEY, mapOpt: Taro.chooseLocation.Option['mapOpts'] = {}) {
const { latitude, longitude, ...opts } = mapOpt
function createLocationChooser (handler, mapOpt: Taro.chooseLocation.Option['mapOpts'] = {}) {
const { key = LOCATION_APIKEY, referer = 'myapp', ...opts } = mapOpt
const query = {
key,
type: 1,
coord: mapOpt.coord ?? [latitude, longitude].every((e) => Number(e) >= 0) ? `${latitude},${longitude}` : undefined,
referer: 'myapp',
referer,
...opts,
}
if (!container) {
const html = `
<div class='taro_choose_location'>
<div class='taro_choose_location_bar'>
<div class='taro_choose_location_back'></div>
<p class='taro_choose_location_title'>位置</p>
<button class='taro_choose_location_submit'>完成</button>
</div>
<iframe class='taro_choose_location_frame' frameborder='0' src="https://apis.map.qq.com/tools/locpicker?${stringify(
query,
{ arrayFormat: 'comma', skipNull: true }
)}" />
</div>
`
<div class='taro_choose_location'>
<div class='taro_choose_location_bar'>
<div class='taro_choose_location_back'></div>
<p class='taro_choose_location_title'>位置</p>
<button class='taro_choose_location_submit'>完成</button>
</div>
<iframe id='map-iframe' class='taro_choose_location_frame' frameborder='0' src="https://apis.map.qq.com/tools/locpicker?${stringify(query,{ arrayFormat: 'comma', skipNull: true })}"/>
</div>
`
container = document.createElement('div')
container.innerHTML = html
}
Expand Down Expand Up @@ -76,20 +72,9 @@ function createLocationChooser (handler, key = LOCATION_APIKEY, mapOpt: Taro.cho
* 打开地图选择位置。
*/
export const chooseLocation: typeof Taro.chooseLocation = ({ success, fail, complete, mapOpts } = {}) => {
const key = LOCATION_APIKEY
const handle = new MethodHandler({ name: 'chooseLocation', success, fail, complete })
return new Promise((resolve, reject) => {
const chooseLocation: Partial<Taro.chooseLocation.SuccessCallbackResult> = {}
if (!key) {
console.warn('chooseLocation api 依赖腾讯地图定位api,需要在 defineConstants 中配置 LOCATION_APIKEY')
return handle.fail(
{
errMsg: 'LOCATION_APIKEY needed',
},
{ resolve, reject }
)
}

const onMessage = (event) => {
// 接收位置信息,用户选择确认位置点后选点组件会触发该事件,回传用户的位置信息
const loc = event.data
Expand Down Expand Up @@ -119,12 +104,10 @@ export const chooseLocation: typeof Taro.chooseLocation = ({ success, fail, comp
}
}
},
key,
mapOpts
)

document.body.appendChild(chooser.container)

window.addEventListener('message', onMessage, false)
chooser.show()
})
Expand Down
76 changes: 76 additions & 0 deletions packages/taro-mpharmony/src/api/location/getFuzzyLocation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import Taro from '@tarojs/taro'
import { shouldBeObject } from 'src/utils'
import { wgs84Togcj02 } from 'src/utils/coordinateConvert'

import { MethodHandler } from '../../utils/handler'

export const getFuzzyLocation: typeof Taro.getFuzzyLocation = (options) => {
const name = 'getFuzzyLocation'
// options must be an Object
const isObject = shouldBeObject(options)
if (!isObject.flag) {
const res = { errMsg: `${name}:fail ${isObject.msg}` }
console.error(res.errMsg)
return Promise.reject(res)
}
const {
type = 'wgs84',
success,
fail,
complete
} = options as Exclude<typeof options, undefined>
const handle = new MethodHandler({ name, success, fail, complete })

return new Promise<Taro.getFuzzyLocation.SuccessCallbackResult>((resolve, reject) => {
const fuzzyLocation: Partial<Taro.getFuzzyLocation.SuccessCallbackResult> = {}
let flag = true

// 默认10秒未获取则返回超时
const timeoutId = setTimeout(function () {
if (!fuzzyLocation.latitude && !fuzzyLocation.longitude) {
const result: TaroGeneral.CallbackResult = {
errMsg: '定位超时!'
}
flag = false
handle.fail(result, { resolve, reject })
}
}, 10000)

// @ts-ignore
native.getLocation({
success: (res: any) => {
// 超时后即使后面回调触发了也不后面的逻辑
if (!flag) {
return
}
const lat = res.latitude
const lng = res.longitude
// 鸿蒙默认返回的是wgs84坐标
if (type === 'gcj02') {
const ret = wgs84Togcj02(lng, lat)
fuzzyLocation.latitude = parseFloat(ret[1].toFixed(6))
fuzzyLocation.longitude = parseFloat(ret[0].toFixed(6))
} else if (type === 'wgs84') {
fuzzyLocation.latitude = parseFloat(lat.toFixed(6))
fuzzyLocation.longitude = parseFloat(lng.toFixed(6))
} else {
const result: TaroGeneral.CallbackResult = {
errMsg: 'type参数有误,仅支持"wgs84"和"gcj02"坐标系!'
}
clearTimeout(timeoutId)
return handle.fail(result, { resolve, reject })
}
handle.success(fuzzyLocation, { resolve, reject })
},
fail: (res: any) => {
if (!flag) {
return
}
const result: TaroGeneral.CallbackResult = {
errMsg: `${name}:fail errCode: ${res.errCode}`
}
handle.fail(result, { resolve, reject })
}
})
})
}
56 changes: 51 additions & 5 deletions packages/taro-mpharmony/src/api/location/getLocation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Taro from '@tarojs/taro'
import { shouldBeObject } from 'src/utils'
import { wgs84Togcj02 } from 'src/utils/coordinateConvert'

import { MethodHandler } from '../../utils/handler'

Expand All @@ -12,25 +13,67 @@ export const getLocation: typeof Taro.getLocation = (options) => {
console.error(res.errMsg)
return Promise.reject(res)
}
const { success, fail, complete } = options as Exclude<typeof options, undefined>

const {
altitude = 'false',
highAccuracyExpireTime,
isHighAccuracy = false,
type = 'wgs84',
success,
fail,
complete
} = options as Exclude<typeof options, undefined>
const handle = new MethodHandler({ name, success, fail, complete })

return new Promise<Taro.getLocation.SuccessCallbackResult>((resolve, reject) => {
const loc: Partial<Taro.getLocation.SuccessCallbackResult> = {}
let flag = true

const timeoutId = setTimeout(function () {
if (!loc.latitude && !loc.longitude) {
const result: TaroGeneral.CallbackResult = {
errMsg: '定位超时!'
}
flag = false
handle.fail(result, { resolve, reject })
}
}, highAccuracyExpireTime)

// @ts-ignore
native.getLocation({
success: (res: any) => {
// 超时后即使后面回调触发了也不后面的逻辑
if (!flag) {
return
}
// 鸿蒙默认返回的是高精度定位的位置信息
const lat = res.latitude
const lng = res.longitude
// 鸿蒙默认返回的是wgs84坐标
if (type === 'gcj02') {
const ret = wgs84Togcj02(lng, lat)
loc.latitude = isHighAccuracy ? ret[1] : parseFloat(ret[1].toFixed(6))
loc.longitude = isHighAccuracy ? ret[0] : parseFloat(ret[0].toFixed(6))
} else if (type === 'wgs84') {
loc.latitude = isHighAccuracy ? lat : parseFloat(lat.toFixed(6))
loc.longitude = isHighAccuracy ? lng : parseFloat(lng.toFixed(6))
} else {
const result: TaroGeneral.CallbackResult = {
errMsg: 'type参数有误,仅支持"wgs84"和"gcj02"坐标系!'
}
clearTimeout(timeoutId)
return handle.fail(result, { resolve, reject })
}
const result: Taro.getLocation.SuccessCallbackResult = {
/** 位置的精确度 */
accuracy: res.accuracy,
/** 高度,单位 m */
altitude: res.altitude,
altitude: JSON.parse(altitude) ? res.altitude : 0,
/** 水平精度,单位 m */
horizontalAccuracy: res.accuracy,
/** 纬度,范围为 -90~90,负数表示南纬 */
latitude: res.latitude,
latitude: loc.latitude as number,
/** 经度,范围为 -180~180,负数表示西经 */
longitude: res.longitude,
longitude: loc.longitude as number,
/** 速度,单位 m/s */
speed: res.speed,
/** 垂直精度,单位 m */
Expand All @@ -41,6 +84,9 @@ export const getLocation: typeof Taro.getLocation = (options) => {
handle.success(result, { resolve, reject })
},
fail: (res: any) => {
if (!flag) {
return
}
handle.fail(res, { resolve, reject })
},
})
Expand Down
24 changes: 9 additions & 15 deletions packages/taro-mpharmony/src/api/location/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
import { processOpenApi, temporarilyNotSupport } from '../../utils/index'
import { temporarilyNotSupport } from '../../utils/index'

// 位置
export * from './startLocationUpdate'
export * from './startLocationUpdateBackground'
export * from './stopLocationUpdate'

export const openLocation = /* @__PURE__ */ processOpenApi({
name: 'openLocation',
defaultOptions: { scale: 18 },
})

export { getLocation } from './getLocation'
export * from './chooseLocation'
export * from './getFuzzyLocation'
export * from './getLocation'
export * from './offLocationChange'
export * from './offLocationChangeError'
export * from './onLocationChange'
export * from './onLocationChangeError'
export * from './openLocation'
export * from './startLocationUpdate'
export * from './startLocationUpdateBackground'
export * from './stopLocationUpdate'

export const choosePoi = /* @__PURE__ */ temporarilyNotSupport('choosePoi')
export const getFuzzyLocation = /* @__PURE__ */ temporarilyNotSupport('getFuzzyLocation')

export { chooseLocation } from './chooseLocation'
export const choosePoi = /* @__PURE__ */ temporarilyNotSupport('choosePoi')
Loading

0 comments on commit 5ac211c

Please sign in to comment.