Commit 5b69a9e6 by 李伟康

提交

0 parents
node_modules
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
{
"name": "glmap-jssdk",
"version": "1.0.0",
"description": "glmap-jssdk",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "parcel build src/index.js --out-file dist/glmap-jssdk.js"
},
"author": "liwk",
"license": "ISC",
"devDependencies": {
"parcel-bundler": "^1.12.5"
}
}
import md5 from '../lib/md5'
import qs from '../lib/qs'
const domain = 'https://restapi.amap.com',
KEY = '373bd88fa36ebc0247d60281386b6cec',
SECRET = 'a2a93fa04721a36819d86b71cb31fe41'
class GlMap {
constructor(params = {}) {
this.key = params.key || KEY
this.secret = params.secret || SECRET
}
/**对参数进行排序:按参数名升序 */
setLocaleCompare (params) {
params.key = this.key
let keys = [],
obj = {}
Object.keys(params).map(e => keys.push(e))
keys.sort((a, b) => a.localeCompare(b)).map(e => (obj[e] = params[e]))
return obj
}
/**签名计算(sig) */
getSign (params) {
return md5(`${decodeURIComponent(qs.stringify(this.setLocaleCompare(params)))}${this.secret}`)
}
/**封装的GET方法 */
get (method, data) {
return this.request('GET', method, data)
}
/**封装的请求方法 */
request (RequestMethods, method, data) {
if (!data) data = {}
const sig = this.getSign(data, method),
ISMiniprogram = wx && wx.request,
obj = {
...this.setLocaleCompare(data),
sig
}
if (ISMiniprogram) {
wx.showNavigationBarLoading()
let header = RequestMethods === 'POST' ? {
'content-type': 'application/json'
} : {}
return new Promise((resolve, reject) => {
wx.request({
url: `${domain}${method}`,
data: obj,
method: RequestMethods,
header,
dataType: 'json',
responseType: 'text',
success ({
statusCode,
data,
errMsg
}) {
if (statusCode == '200') {
if (data.status == '1') {
resolve(data)
} else {
wx.showToast({
title: data.info,
icon: 'none'
})
}
} else {
wx.showToast({
title: errMsg,
icon: 'error'
})
}
},
fail (error) {
wx.hideLoading()
console.error(`接口异常:`, error)
wx.showToast({
title: '系统异常',
icon: 'error'
})
reject(error)
},
complete () {
wx.hideNavigationBarLoading()
}
})
})
} else {
const params = []
Object.keys(obj).map(key => {
params.push(`${key}=${encodeURIComponent(obj[key])}`)
})
return new Promise((resolve, reject) => {
window.fetch(`${domain}${method}?${params.join('&')}`, {
method: RequestMethods,
}).then(async res => {
try {
const data = await res.json()
if (data.status == '1') resolve(data)
else throw data.info
} catch (error) {
alert(error)
reject()
}
})
})
}
}
/**计算距离
* from 起始位置 [lat,lng]
* to 结束位置 [lat,lng]
* type 0:直线距离 , 1:驾车导航距离(仅支持国内坐标) , 3:步行规划距离(仅支持5km之间的距离)
*/
async calculateDistance (from, to, type = 1) {
try {
const destination = JSON.parse(JSON.stringify(from)).reverse().join(','),
origins = JSON.parse(JSON.stringify(to)).reverse().join(','),
{
results
} = await this.get('/v3/distance', {
destination,
origins,
type
}),
res = {
elements: results
}
return Promise.resolve(res)
} catch (error) {
return Promise.reject(error)
}
}
/** 批量距离计算(矩阵)
* from 起始位置 [lat,lng]
* toList 重点位置 [[lat,lng],[lat,lng]]
* type 0:直线距离 , 1:驾车导航距离(仅支持国内坐标) , 3:步行规划距离(仅支持5km之间的距离)
*/
async calculateDistanceMatrix (from, toList, type = 1) {
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.get('/v3/distance', {
destination,
origins,
type
}),
res = {
rows: [{
elements: results
}]
}
return Promise.resolve(res)
} catch (error) {
return Promise.reject(error)
}
}
/**地址解析(地址转坐标)
* address (String)
*/
geocoder (address) {
return this.get('/v3/geocode/geo', {
address
})
}
/**逆地址解析(坐标位置描述)
* location [lat<纬度>,lng<经度>] */
async detailedAdrress (location) {
try {
const [lat, lng] = location
const {
regeocode
} = await this.get('/v3/geocode/regeo',
{
location: JSON.parse(JSON.stringify(location)).reverse().join(',')
}), {
addressComponent,
formatted_address
} = regeocode,
address = `${addressComponent.province || ''}${addressComponent.city || ''}${addressComponent.district || ''}${addressComponent.township || ''}`,
data = {
...regeocode,
address,
formatted_addresses: {
recommend: formatted_address,
rough: formatted_address,
standard_address: formatted_address
},
address_component: {
city: addressComponent.city,
district: addressComponent.district,
nation: addressComponent.country,
province: addressComponent.province,
street: addressComponent.township
},
ad_info: {
adcode: addressComponent.adcode,
city: addressComponent.city,
city_code: addressComponent.citycode,
district: addressComponent.district,
location: {
lat,
lng
},
name: `${addressComponent.country + ',' || ''}${addressComponent.province + ',' || ''}${addressComponent.city + ',' || ''}${addressComponent.district || ''}`,
nation: addressComponent.country,
nation_code: '',
phone_area_code: addressComponent.citycode,
province: addressComponent.province
},
location: {
lat,
lng
}
}
return Promise.resolve(data)
} catch (error) {
return Promise.reject(error)
}
}
/**IP定位 */
getLocationByIp () {
return this.get('/v3/ip')
}
/**坐标转换
* locationsList:[[lat,lng],[lat,lng]] 纬度前,经度后 (最多支持40对坐标)
* coordsys 原坐标系(可选值:
gps;
mapbar;
baidu;
autonavi(不进行转换))
*
*/
translate (locationsList, coordsys = 'autonavi') {
const locations = JSON.parse(JSON.stringify(locationsList)).map(e => e = e.reverse()).join('|')
return this.get('/v3/assistant/coordinate/convert', {
locations,
coordsys
})
}
}
export default GlMap
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!