Commit 537fa924 by 李伟康

替换为百度

1 parent 6f0e04f8
{
"name": "glsx-map-sdk",
"version": "0.1.0",
"version": "0.2.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "glsx-map-sdk",
"version": "0.1.0",
"version": "0.2.0",
"license": "ISC",
"devDependencies": {
"rollup": "^1.32.1",
......
{
"name": "glsx-map-sdk",
"version": "0.2.0",
"version": "0.3.0",
"description": "glsx-map-sdk",
"main": "src/index.js",
"scripts": {
......
......@@ -7,4 +7,4 @@
* @LastEditTime: 2023-07-05 08:48:32
* @FilePath: \glsx-map-sdk\src\constants.js
*/
export const MAP_OPTIONS = { domain: 'https://restapi.amap.com', KEY: '373bd88fa36ebc0247d60281386b6cec', SECRET: 'a2a93fa04721a36819d86b71cb31fe41' }
export const MAP_OPTIONS = { domain: 'https://api.map.baidu.com', KEY: 'bBk6VKyCi8pmGnnvTsSr6ULPY86JdBCV'}
......@@ -14,6 +14,26 @@ class GlMapApi {
this.request = new Request(key, secret)
}
/**
* 使用 Haversine 公式计算两个坐标点之间的直线距离
* @param {Array} from - 起始位置 [纬度, 经度]
* @param {Array} to - 结束位置 [纬度, 经度]
* @returns {number} - 返回两点之间的直线距离(单位:米)
*/
calculateHaversineDistance (from, to) {
const R = 6371e3; // 地球半径,单位:米
const φ1 = (from[0] * Math.PI) / 180; // 起点纬度转换为弧度
const φ2 = (to[0] * Math.PI) / 180; // 终点纬度转换为弧度
const Δφ = ((to[0] - from[0]) * Math.PI) / 180; // 纬度差
const Δλ = ((to[1] - from[1]) * Math.PI) / 180; // 经度差
const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // 距离,单位:米
}
/**
* 定义一个异步方法,用于计算两个坐标之间的距离
* @param {*} from 起始位置 [lat,lng]
* @param {*} to 结束位置 [lat,lng]
......@@ -21,18 +41,32 @@ class GlMapApi {
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
* @returns {Promise<{elements: Array}>}
*/
async calculateDistance(from, to, type = 1, $attrs = {}) {
async calculateDistance (from, to, type = 1, $attrs = {}) {
try {
const destination = JSON.parse(JSON.stringify(from)).reverse().join(','),
origins = JSON.parse(JSON.stringify(to)).reverse().join(','),
{ results } = await this.request.get('/v3/distance', {
if (type == 0) {
const distance = this.calculateHaversineDistance(from, to)
return {
elements: [
{
distance
}
]
}
}
const distanceType = {
1: 'driving',
2: 'riding',
3: 'walking'
},
destination = JSON.parse(JSON.stringify(from)).join(','),
origin = JSON.parse(JSON.stringify(to)).join(','),
{ routes } = await this.request.get(`/direction/v2/${distanceType[type]}`, {
destination,
origins,
type,
origin,
...$attrs
})
return {
elements: results
elements: routes[0]
}
} catch (error) {
throw error
......@@ -46,16 +80,16 @@ class GlMapApi {
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
* @returns {Promise<{rows: Array}>}
*/
async calculateDistanceMatrix(from, toList, type = 1, $attrs = {}) {
async calculateDistanceMatrix (from, toList, type = 1, $attrs = {}) {
try {
const destination = JSON.parse(JSON.stringify(from)).reverse().join(','),
origins = JSON.parse(JSON.stringify(toList))
.map(e => (e = e.reverse()))
.join('|'),
{ results } = await this.request.get('/v3/distance', {
destination,
const distanceMatrixType = {
1: 'driving',
3: 'walking'
}, origins = JSON.parse(JSON.stringify(from)).join(','),
destinations = JSON.parse(JSON.stringify(toList)).join('|'),
results = await this.request.get(`/routematrix/v2/${distanceMatrixType[type]}`, {
destinations,
origins,
type,
...$attrs
}),
res = {
......@@ -77,8 +111,8 @@ class GlMapApi {
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
* @returns
*/
geocoder(address, $attrs = {}) {
return this.request.get('/v3/geocode/geo', {
geocoder (address, $attrs = {}) {
return this.request.get('/geocoding/v3', {
address,
...$attrs
})
......@@ -89,17 +123,18 @@ class GlMapApi {
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
* @returns
*/
async detailedAdrress(location, $attrs = {}) {
async detailedAdrress (location, $attrs = {}) {
try {
const [lat, lng] = location
const { regeocode } = await this.request.get('/v3/geocode/regeo', {
location: JSON.parse(JSON.stringify(location)).reverse().join(','),
const result = await this.request.get('/reverse_geocoding/v3',
{
location: `${lat},${lng}}`,
...$attrs
}),
{ addressComponent, formatted_address } = regeocode,
address = `${addressComponent.province || ''}${addressComponent.city || ''}${addressComponent.district || ''}${addressComponent.township || ''}`,
})
const { addressComponent, formatted_address, cityCode } = result
const address = `${addressComponent.province || ''}${addressComponent.city || ''}${addressComponent.district || ''}${addressComponent.town || ''}`,
data = {
...regeocode,
...result,
address,
formatted_addresses: {
recommend: formatted_address,
......@@ -111,12 +146,12 @@ class GlMapApi {
district: addressComponent.district,
nation: addressComponent.country,
province: addressComponent.province,
street: addressComponent.township
street: addressComponent.town
},
ad_info: {
adcode: addressComponent.adcode,
city: addressComponent.city,
city_code: addressComponent.citycode,
city_code: cityCode,
district: addressComponent.district,
location: {
lat,
......@@ -125,7 +160,7 @@ class GlMapApi {
name: `${addressComponent.country + ',' || ''}${addressComponent.province + ',' || ''}${addressComponent.city + ',' || ''}${addressComponent.district || ''}`,
nation: addressComponent.country,
nation_code: '',
phone_area_code: addressComponent.citycode,
phone_area_code: cityCode,
province: addressComponent.province
},
location: {
......@@ -143,29 +178,30 @@ class GlMapApi {
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
* @returns
*/
getLocationByIp($attrs = {}) {
return this.request.get('/v3/ip', $attrs)
getLocationByIp ($attrs = {}) {
return this.request.get('/location/ip', $attrs)
}
/**
* 坐标转换用于将一组坐标转换为不同的坐标系
* @param {*} locationsList [[lat,lng],[lat,lng]] 纬度前,经度后 (最多支持40对坐标)
* @param {*} coordsys 原坐标系(可选值:
gps;
mapbar;
baidu;
autonavi(不进行转换))
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
* @param {*} model 原坐标系(可选值:
转换方式可选值:
1:amap/tencent to bd09ll
2:gps to bd09ll
3:bd09ll to bd09mc
4:bd09mc to bd09ll
5:bd09ll to amap/tencent
6:bd09mc to amap/tencent
* @param {*} $attrs 自定义入参 参考https://lbsyun.baidu.com/faq/api?title=webapi/guide/changeposition-base
* @returns
*/
translate(locationsList, coordsys = 'autonavi', $attrs = {}) {
// 使用数组解构和map方法,将locationsList参数转换为字符串,并反转数组顺序,然后用竖线连接,得到locations字符串
const locations = JSON.parse(JSON.stringify(locationsList))
.map(e => (e = e.reverse()))
.join('|')
// 调用request对象的get方法,传入请求路径为/v3/assistant/coordinate/convert,请求数据为locations字符串和coordsys参数(默认为autonavi),并返回结果
return this.request.get('/v3/assistant/coordinate/convert', {
locations,
coordsys,
translate (locationsList, model = 1, $attrs = {}) {
// 使用数组解构和map方法,将locationsList参数转换为字符串,并反转数组顺序,然后用;连接,得到locations字符串
const coords = JSON.parse(JSON.stringify(locationsList)).map(e => (e = e.reverse()))
.join(';')
return this.request.get('/geoconv/v2/', {
coords,
model,
...$attrs
})
}
......@@ -178,21 +214,20 @@ class GlMapApi {
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
*/
async routePlanning(from, to, type = 3, $attrs = {}) {
const funName = {
1: '/v3/direction/walking',
2: '/v4/direction/bicycling',
3: '/v3/direction/driving'
}[type],
origin = JSON.parse(JSON.stringify(from)).reverse().join(','),
destination = JSON.parse(JSON.stringify(to)).reverse().join(',')
async routePlanning (from, to, type = 3, $attrs = {}) {
try {
const { route } = await this.request.get(funName, {
origin,
destination,
...$attrs
})
return Promise.resolve(route)
const distanceMatrixType = {
3: 'driving',
2: 'riding',
1: 'walking'
}, origin = JSON.parse(JSON.stringify(from)).join(','),
destination = JSON.parse(JSON.stringify(to)).join(','),
{ routes } = await this.request.get(`/direction/v2/${distanceMatrixType[type]}`, {
destination,
origin,
...$attrs
})
return Promise.resolve(routes)
} catch (error) {
return Promise.reject(error)
}
......@@ -203,14 +238,14 @@ class GlMapApi {
* @param {*} location 定位坐标 [lat,lng] 纬度前,经度后
* @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
*/
async keywordSearch(keywords, location, $attrs = {}) {
async keywordSearch (query, location = [], $attrs = {}) {
try {
const { tips } = await this.request.get('/v3/assistant/inputtips', {
keywords,
location: JSON.parse(JSON.stringify(location)).reverse().join(','),
const result = await this.request.get('/place/v2/suggestion', {
query,
location: JSON.parse(JSON.stringify(location)).join(','),
...$attrs
})
return Promise.resolve(tips)
return Promise.resolve(result)
} catch (error) {
return Promise.reject(error)
}
......
......@@ -20,22 +20,23 @@ class Request {
}
/**对参数进行排序:按参数名升序 */
setLocaleCompare(params) {
setLocaleCompare (params) {
// 将key添加到参数对象中
params.key = this.key
params.ak = this.key
params.output = 'json'
return Object.fromEntries(Object.entries(params).sort(([a], [b]) => a.localeCompare(b)))
}
/**签名计算(sig) */
getSign(params) {
getSign (params) {
return md5(`${decodeURIComponent(qs.stringify(this.setLocaleCompare(params)))}${this.secret}`)
}
/**封装的GET方法 */
get(method, data) {
get (method, data) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.request('GET', method, data)
}
/**封装的请求方法 */
async request(RequestMethods, method, data = {}) {
async request (RequestMethods, method, data = {}) {
// 调用getSign方法,传入请求数据和请求路径,得到签名
const sig = this.getSign(data, method),
obj = {
......@@ -45,39 +46,28 @@ class Request {
if (isMiniprogram) {
wx.showNavigationBarLoading()
try {
const res = await new Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${MAP_OPTIONS.domain}${method}`,
data: obj,
method: RequestMethods,
header:
RequestMethods === 'POST'
? {
'content-type': 'application/json'
}
: {},
dataType: 'json',
responseType: 'text',
success: resolve,
header: {
'content-type': 'application/json'
},
success: ({ data }) => {
const { status, result } = data
if (0 === status) {
resolve(result ? result : data)
} else {
wx.showToast({
title: 'errMsg',
icon: 'error'
})
}
},
fail: reject
})
})
const { statusCode, data, errMsg } = res
if (statusCode == '200') {
if (data.status == '1') {
return data
} else {
wx.showToast({
title: data.info,
icon: 'none'
})
}
} else {
wx.showToast({
title: errMsg,
icon: 'error'
})
}
} catch (error) {
wx.hideLoading()
console.error(`接口异常:`, error)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!