提交 2d46131a 编写于 作者: Q qiang

Merge branch 'dev' into alpha

# Conflicts:
#	packages/uni-stacktracey/package.json
...@@ -14,6 +14,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s ...@@ -14,6 +14,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s
const OPERATING_TIME = 10; // 数据上报时间 单位s const OPERATING_TIME = 10; // 数据上报时间 单位s
const DIFF_TIME = 60 * 1000 * 60 * 24; const DIFF_TIME = 60 * 1000 * 60 * 24;
// 获取 manifest.json 中统计配置
const uniStatisticsConfig = process.env.UNI_STATISTICS_CONFIG;
let statConfig = { let statConfig = {
appid: process.env.UNI_APP_ID, appid: process.env.UNI_APP_ID,
}; };
...@@ -471,7 +473,8 @@ const is_debug = debug; ...@@ -471,7 +473,8 @@ const is_debug = debug;
* 日志输出 * 日志输出
* @param {*} data * @param {*} data
*/ */
const log = (data) => { const log = (data, type) => {
let msg_type = ''; let msg_type = '';
switch (data.lt) { switch (data.lt) {
case '1': case '1':
...@@ -494,11 +497,41 @@ const log = (data) => { ...@@ -494,11 +497,41 @@ const log = (data) => {
msg_type = 'PUSH'; msg_type = 'PUSH';
break break
} }
// #ifdef APP
// 在 app 中,日志转为 字符串
if(typeof data === 'object') {
data = JSON.stringify(data);
}
// #endif
if (type) {
console.log(`=== 统计队列数据上报 ===`);
console.log(data);
console.log(`=== 上报结束 ===`);
return
}
if (msg_type) { if (msg_type) {
console.log(`=== 统计数据采集:${msg_type} ===`); console.log(`=== 统计数据采集:${msg_type} ===`);
console.log(data); console.log(data);
console.log(`=== 采集结束 ===`); console.log(`=== 采集结束 ===`);
} }
};
/**
* 获取上报时间间隔
* @param {*} defaultTime 默认上报间隔时间 单位s
*/
const get_report_Interval = (defaultTime) => {
let time = uniStatisticsConfig.reportInterval;
// 如果上报时间配置为0 相当于立即上报
if (Number(time) === 0) return 0
time = time || defaultTime;
let reg = /(^[1-9]\d*$)/;
// 如果不是整数,则默认为上报间隔时间
if (!reg.test(time)) return defaultTime
return Number(time)
}; };
const appid = process.env.UNI_APP_ID; // 做应用隔离 const appid = process.env.UNI_APP_ID; // 做应用隔离
...@@ -672,6 +705,7 @@ const get_residence_time = (type) => { ...@@ -672,6 +705,7 @@ const get_residence_time = (type) => {
} }
}; };
const eport_Interval = get_report_Interval(OPERATING_TIME);
// 统计数据默认值 // 统计数据默认值
let statData = { let statData = {
uuid: get_uuid(), // 设备标识 uuid: get_uuid(), // 设备标识
...@@ -1131,7 +1165,7 @@ class Report { ...@@ -1131,7 +1165,7 @@ class Report {
log(data); log(data);
} }
// 判断时候到达上报时间 ,默认 10 秒上报 // 判断时候到达上报时间 ,默认 10 秒上报
if (page_residence_time < OPERATING_TIME && !type) return if (page_residence_time < eport_Interval && !type) return
// 时间超过,重新获取时间戳 // 时间超过,重新获取时间戳
set_page_residence_time(); set_page_residence_time();
...@@ -1167,7 +1201,9 @@ class Report { ...@@ -1167,7 +1201,9 @@ class Report {
sendRequest(optionsData) { sendRequest(optionsData) {
{ {
if (!uni.__stat_uniCloud_space) { if (!uni.__stat_uniCloud_space) {
console.error('应用未关联服务空间,统计上报失败,请在uniCloud目录右键关联服务空间.'); console.error(
'应用未关联服务空间,统计上报失败,请在uniCloud目录右键关联服务空间.'
);
return return
} }
...@@ -1181,9 +1217,7 @@ class Report { ...@@ -1181,9 +1217,7 @@ class Report {
.report(optionsData) .report(optionsData)
.then(() => { .then(() => {
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(optionsData, true);
console.log(optionsData);
console.log(`=== 上报结束 ===`);
} }
}) })
.catch((err) => { .catch((err) => {
...@@ -1204,9 +1238,7 @@ class Report { ...@@ -1204,9 +1238,7 @@ class Report {
let options = get_sgin(get_encodeURIComponent_options(data)).options; let options = get_sgin(get_encodeURIComponent_options(data)).options;
image.src = STAT_H5_URL + '?' + options; image.src = STAT_H5_URL + '?' + options;
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(data, true);
console.log(data);
console.log(`=== 上报结束 ===`);
} }
}); });
} }
...@@ -1254,6 +1286,10 @@ class Stat extends Report { ...@@ -1254,6 +1286,10 @@ class Stat extends Report {
// '=== 当前绑定的统计服务空间spaceId:' + // '=== 当前绑定的统计服务空间spaceId:' +
// uni.__stat_uniCloud_space.config.spaceId // uni.__stat_uniCloud_space.config.spaceId
// ) // )
} else {
console.error(
'应用未关联服务空间,请在uniCloud目录右键关联服务空间'
);
} }
} }
} }
......
...@@ -12,6 +12,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s ...@@ -12,6 +12,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s
const OPERATING_TIME = 10; // 数据上报时间 单位s const OPERATING_TIME = 10; // 数据上报时间 单位s
const DIFF_TIME = 60 * 1000 * 60 * 24; const DIFF_TIME = 60 * 1000 * 60 * 24;
// 获取 manifest.json 中统计配置
const uniStatisticsConfig = process.env.UNI_STATISTICS_CONFIG;
let statConfig = { let statConfig = {
appid: process.env.UNI_APP_ID, appid: process.env.UNI_APP_ID,
}; };
...@@ -469,7 +471,8 @@ const is_debug = debug; ...@@ -469,7 +471,8 @@ const is_debug = debug;
* 日志输出 * 日志输出
* @param {*} data * @param {*} data
*/ */
const log = (data) => { const log = (data, type) => {
let msg_type = ''; let msg_type = '';
switch (data.lt) { switch (data.lt) {
case '1': case '1':
...@@ -492,11 +495,41 @@ const log = (data) => { ...@@ -492,11 +495,41 @@ const log = (data) => {
msg_type = 'PUSH'; msg_type = 'PUSH';
break break
} }
// #ifdef APP
// 在 app 中,日志转为 字符串
if(typeof data === 'object') {
data = JSON.stringify(data);
}
// #endif
if (type) {
console.log(`=== 统计队列数据上报 ===`);
console.log(data);
console.log(`=== 上报结束 ===`);
return
}
if (msg_type) { if (msg_type) {
console.log(`=== 统计数据采集:${msg_type} ===`); console.log(`=== 统计数据采集:${msg_type} ===`);
console.log(data); console.log(data);
console.log(`=== 采集结束 ===`); console.log(`=== 采集结束 ===`);
} }
};
/**
* 获取上报时间间隔
* @param {*} defaultTime 默认上报间隔时间 单位s
*/
const get_report_Interval = (defaultTime) => {
let time = uniStatisticsConfig.reportInterval;
// 如果上报时间配置为0 相当于立即上报
if (Number(time) === 0) return 0
time = time || defaultTime;
let reg = /(^[1-9]\d*$)/;
// 如果不是整数,则默认为上报间隔时间
if (!reg.test(time)) return defaultTime
return Number(time)
}; };
const appid = process.env.UNI_APP_ID; // 做应用隔离 const appid = process.env.UNI_APP_ID; // 做应用隔离
...@@ -670,6 +703,7 @@ const get_residence_time = (type) => { ...@@ -670,6 +703,7 @@ const get_residence_time = (type) => {
} }
}; };
const eport_Interval = get_report_Interval(OPERATING_TIME);
// 统计数据默认值 // 统计数据默认值
let statData = { let statData = {
uuid: get_uuid(), // 设备标识 uuid: get_uuid(), // 设备标识
...@@ -1129,7 +1163,7 @@ class Report { ...@@ -1129,7 +1163,7 @@ class Report {
log(data); log(data);
} }
// 判断时候到达上报时间 ,默认 10 秒上报 // 判断时候到达上报时间 ,默认 10 秒上报
if (page_residence_time < OPERATING_TIME && !type) return if (page_residence_time < eport_Interval && !type) return
// 时间超过,重新获取时间戳 // 时间超过,重新获取时间戳
set_page_residence_time(); set_page_residence_time();
...@@ -1165,7 +1199,9 @@ class Report { ...@@ -1165,7 +1199,9 @@ class Report {
sendRequest(optionsData) { sendRequest(optionsData) {
{ {
if (!uni.__stat_uniCloud_space) { if (!uni.__stat_uniCloud_space) {
console.error('应用未关联服务空间,统计上报失败,请在uniCloud目录右键关联服务空间.'); console.error(
'应用未关联服务空间,统计上报失败,请在uniCloud目录右键关联服务空间.'
);
return return
} }
...@@ -1179,9 +1215,7 @@ class Report { ...@@ -1179,9 +1215,7 @@ class Report {
.report(optionsData) .report(optionsData)
.then(() => { .then(() => {
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(optionsData, true);
console.log(optionsData);
console.log(`=== 上报结束 ===`);
} }
}) })
.catch((err) => { .catch((err) => {
...@@ -1202,9 +1236,7 @@ class Report { ...@@ -1202,9 +1236,7 @@ class Report {
let options = get_sgin(get_encodeURIComponent_options(data)).options; let options = get_sgin(get_encodeURIComponent_options(data)).options;
image.src = STAT_H5_URL + '?' + options; image.src = STAT_H5_URL + '?' + options;
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(data, true);
console.log(data);
console.log(`=== 上报结束 ===`);
} }
}); });
} }
...@@ -1252,6 +1284,10 @@ class Stat extends Report { ...@@ -1252,6 +1284,10 @@ class Stat extends Report {
// '=== 当前绑定的统计服务空间spaceId:' + // '=== 当前绑定的统计服务空间spaceId:' +
// uni.__stat_uniCloud_space.config.spaceId // uni.__stat_uniCloud_space.config.spaceId
// ) // )
} else {
console.error(
'应用未关联服务空间,请在uniCloud目录右键关联服务空间'
);
} }
} }
} }
......
...@@ -14,6 +14,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s ...@@ -14,6 +14,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s
const OPERATING_TIME = 10; // 数据上报时间 单位s const OPERATING_TIME = 10; // 数据上报时间 单位s
const DIFF_TIME = 60 * 1000 * 60 * 24; const DIFF_TIME = 60 * 1000 * 60 * 24;
// 获取 manifest.json 中统计配置
const uniStatisticsConfig = process.env.UNI_STATISTICS_CONFIG;
let statConfig = { let statConfig = {
appid: process.env.UNI_APP_ID, appid: process.env.UNI_APP_ID,
}; };
...@@ -450,7 +452,8 @@ const is_debug = debug; ...@@ -450,7 +452,8 @@ const is_debug = debug;
* 日志输出 * 日志输出
* @param {*} data * @param {*} data
*/ */
const log = (data) => { const log = (data, type) => {
let msg_type = ''; let msg_type = '';
switch (data.lt) { switch (data.lt) {
case '1': case '1':
...@@ -473,11 +476,41 @@ const log = (data) => { ...@@ -473,11 +476,41 @@ const log = (data) => {
msg_type = 'PUSH'; msg_type = 'PUSH';
break break
} }
// #ifdef APP
// 在 app 中,日志转为 字符串
if(typeof data === 'object') {
data = JSON.stringify(data);
}
// #endif
if (type) {
console.log(`=== 统计队列数据上报 ===`);
console.log(data);
console.log(`=== 上报结束 ===`);
return
}
if (msg_type) { if (msg_type) {
console.log(`=== 统计数据采集:${msg_type} ===`); console.log(`=== 统计数据采集:${msg_type} ===`);
console.log(data); console.log(data);
console.log(`=== 采集结束 ===`); console.log(`=== 采集结束 ===`);
} }
};
/**
* 获取上报时间间隔
* @param {*} defaultTime 默认上报间隔时间 单位s
*/
const get_report_Interval = (defaultTime) => {
let time = uniStatisticsConfig.reportInterval;
// 如果上报时间配置为0 相当于立即上报
if (Number(time) === 0) return 0
time = time || defaultTime;
let reg = /(^[1-9]\d*$)/;
// 如果不是整数,则默认为上报间隔时间
if (!reg.test(time)) return defaultTime
return Number(time)
}; };
const appid = process.env.UNI_APP_ID; // 做应用隔离 const appid = process.env.UNI_APP_ID; // 做应用隔离
...@@ -651,6 +684,7 @@ const get_residence_time = (type) => { ...@@ -651,6 +684,7 @@ const get_residence_time = (type) => {
} }
}; };
const eport_Interval = get_report_Interval(OPERATING_TIME);
// 统计数据默认值 // 统计数据默认值
let statData = { let statData = {
uuid: get_uuid(), // 设备标识 uuid: get_uuid(), // 设备标识
...@@ -1117,7 +1151,7 @@ class Report { ...@@ -1117,7 +1151,7 @@ class Report {
log(data); log(data);
} }
// 判断时候到达上报时间 ,默认 10 秒上报 // 判断时候到达上报时间 ,默认 10 秒上报
if (page_residence_time < OPERATING_TIME && !type) return if (page_residence_time < eport_Interval && !type) return
// 时间超过,重新获取时间戳 // 时间超过,重新获取时间戳
set_page_residence_time(); set_page_residence_time();
...@@ -1167,9 +1201,7 @@ class Report { ...@@ -1167,9 +1201,7 @@ class Report {
data: optionsData, data: optionsData,
success: () => { success: () => {
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(optionsData, true);
console.log(optionsData);
console.log(`=== 上报结束 ===`);
} }
}, },
fail: (e) => { fail: (e) => {
...@@ -1197,9 +1229,7 @@ class Report { ...@@ -1197,9 +1229,7 @@ class Report {
let options = get_sgin(get_encodeURIComponent_options(data)).options; let options = get_sgin(get_encodeURIComponent_options(data)).options;
image.src = STAT_H5_URL + '?' + options; image.src = STAT_H5_URL + '?' + options;
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(data, true);
console.log(data);
console.log(`=== 上报结束 ===`);
} }
}); });
} }
......
...@@ -12,6 +12,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s ...@@ -12,6 +12,8 @@ const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s
const OPERATING_TIME = 10; // 数据上报时间 单位s const OPERATING_TIME = 10; // 数据上报时间 单位s
const DIFF_TIME = 60 * 1000 * 60 * 24; const DIFF_TIME = 60 * 1000 * 60 * 24;
// 获取 manifest.json 中统计配置
const uniStatisticsConfig = process.env.UNI_STATISTICS_CONFIG;
let statConfig = { let statConfig = {
appid: process.env.UNI_APP_ID, appid: process.env.UNI_APP_ID,
}; };
...@@ -448,7 +450,8 @@ const is_debug = debug; ...@@ -448,7 +450,8 @@ const is_debug = debug;
* 日志输出 * 日志输出
* @param {*} data * @param {*} data
*/ */
const log = (data) => { const log = (data, type) => {
let msg_type = ''; let msg_type = '';
switch (data.lt) { switch (data.lt) {
case '1': case '1':
...@@ -471,11 +474,41 @@ const log = (data) => { ...@@ -471,11 +474,41 @@ const log = (data) => {
msg_type = 'PUSH'; msg_type = 'PUSH';
break break
} }
// #ifdef APP
// 在 app 中,日志转为 字符串
if(typeof data === 'object') {
data = JSON.stringify(data);
}
// #endif
if (type) {
console.log(`=== 统计队列数据上报 ===`);
console.log(data);
console.log(`=== 上报结束 ===`);
return
}
if (msg_type) { if (msg_type) {
console.log(`=== 统计数据采集:${msg_type} ===`); console.log(`=== 统计数据采集:${msg_type} ===`);
console.log(data); console.log(data);
console.log(`=== 采集结束 ===`); console.log(`=== 采集结束 ===`);
} }
};
/**
* 获取上报时间间隔
* @param {*} defaultTime 默认上报间隔时间 单位s
*/
const get_report_Interval = (defaultTime) => {
let time = uniStatisticsConfig.reportInterval;
// 如果上报时间配置为0 相当于立即上报
if (Number(time) === 0) return 0
time = time || defaultTime;
let reg = /(^[1-9]\d*$)/;
// 如果不是整数,则默认为上报间隔时间
if (!reg.test(time)) return defaultTime
return Number(time)
}; };
const appid = process.env.UNI_APP_ID; // 做应用隔离 const appid = process.env.UNI_APP_ID; // 做应用隔离
...@@ -649,6 +682,7 @@ const get_residence_time = (type) => { ...@@ -649,6 +682,7 @@ const get_residence_time = (type) => {
} }
}; };
const eport_Interval = get_report_Interval(OPERATING_TIME);
// 统计数据默认值 // 统计数据默认值
let statData = { let statData = {
uuid: get_uuid(), // 设备标识 uuid: get_uuid(), // 设备标识
...@@ -1115,7 +1149,7 @@ class Report { ...@@ -1115,7 +1149,7 @@ class Report {
log(data); log(data);
} }
// 判断时候到达上报时间 ,默认 10 秒上报 // 判断时候到达上报时间 ,默认 10 秒上报
if (page_residence_time < OPERATING_TIME && !type) return if (page_residence_time < eport_Interval && !type) return
// 时间超过,重新获取时间戳 // 时间超过,重新获取时间戳
set_page_residence_time(); set_page_residence_time();
...@@ -1165,9 +1199,7 @@ class Report { ...@@ -1165,9 +1199,7 @@ class Report {
data: optionsData, data: optionsData,
success: () => { success: () => {
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(optionsData, true);
console.log(optionsData);
console.log(`=== 上报结束 ===`);
} }
}, },
fail: (e) => { fail: (e) => {
...@@ -1195,9 +1227,7 @@ class Report { ...@@ -1195,9 +1227,7 @@ class Report {
let options = get_sgin(get_encodeURIComponent_options(data)).options; let options = get_sgin(get_encodeURIComponent_options(data)).options;
image.src = STAT_H5_URL + '?' + options; image.src = STAT_H5_URL + '?' + options;
if (is_debug) { if (is_debug) {
console.log(`=== 统计队列数据上报 ===`); log(data, true);
console.log(data);
console.log(`=== 上报结束 ===`);
} }
}); });
} }
......
...@@ -88,7 +88,9 @@ const plugins = [ ...@@ -88,7 +88,9 @@ const plugins = [
RUN_BY_HBUILDERX: process.env.RUN_BY_HBUILDERX, RUN_BY_HBUILDERX: process.env.RUN_BY_HBUILDERX,
UNI_AUTOMATOR_WS_ENDPOINT: JSON.stringify(process.env.UNI_AUTOMATOR_WS_ENDPOINT), UNI_AUTOMATOR_WS_ENDPOINT: JSON.stringify(process.env.UNI_AUTOMATOR_WS_ENDPOINT),
UNI_STAT_UNI_CLOUD: process.env.UNI_STAT_UNI_CLOUD || '""', UNI_STAT_UNI_CLOUD: process.env.UNI_STAT_UNI_CLOUD || '""',
UNI_STAT_DEBUG: process.env.UNI_STAT_DEBUG || '""' UNI_STATISTICS_CONFIG: process.env.UNI_STATISTICS_CONFIG || '""',
UNI_STAT_DEBUG: process.env.UNI_STAT_DEBUG || '""',
UNI_COMPILER_VERSION: JSON.stringify(process.env.UNI_COMPILER_VERSION)
} }
}), }),
new webpack.BannerPlugin({ new webpack.BannerPlugin({
......
...@@ -104,8 +104,9 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) { ...@@ -104,8 +104,9 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) {
'process.env.UNICLOUD_DEBUG': process.env.UNICLOUD_DEBUG, 'process.env.UNICLOUD_DEBUG': process.env.UNICLOUD_DEBUG,
'process.env.RUN_BY_HBUILDERX': process.env.RUN_BY_HBUILDERX, 'process.env.RUN_BY_HBUILDERX': process.env.RUN_BY_HBUILDERX,
'process.env.UNI_AUTOMATOR_WS_ENDPOINT': JSON.stringify(process.env.UNI_AUTOMATOR_WS_ENDPOINT), 'process.env.UNI_AUTOMATOR_WS_ENDPOINT': JSON.stringify(process.env.UNI_AUTOMATOR_WS_ENDPOINT),
'process.env.UNI_STAT_UNI_CLOUD': process.env.UNI_STAT_UNI_CLOUD || '""', 'process.env.UNI_STATISTICS_CONFIG': process.env.UNI_STATISTICS_CONFIG,
'process.env.UNI_STAT_DEBUG': process.env.UNI_STAT_DEBUG || '""', 'process.env.UNI_STAT_UNI_CLOUD': process.env.UNI_STAT_UNI_CLOUD,
'process.env.UNI_STAT_DEBUG': process.env.UNI_STAT_DEBUG,
'process.env.UNI_COMPILER_VERSION': JSON.stringify(process.env.UNI_COMPILER_VERSION), 'process.env.UNI_COMPILER_VERSION': JSON.stringify(process.env.UNI_COMPILER_VERSION),
'process.env.UNI_APP_VERSION_NAME': JSON.stringify(process.env.UNI_APP_VERSION_NAME), 'process.env.UNI_APP_VERSION_NAME': JSON.stringify(process.env.UNI_APP_VERSION_NAME),
'process.env.UNI_APP_VERSION_CODE': JSON.stringify(process.env.UNI_APP_VERSION_CODE) 'process.env.UNI_APP_VERSION_CODE': JSON.stringify(process.env.UNI_APP_VERSION_CODE)
......
...@@ -324,8 +324,9 @@ if ((process.env.UNI_PLATFORM === 'mp-kuaishou' || process.env.UNI_PLATFORM === ...@@ -324,8 +324,9 @@ if ((process.env.UNI_PLATFORM === 'mp-kuaishou' || process.env.UNI_PLATFORM ===
process.env.MERGE_VIRTUAL_HOST_ATTRIBUTES = (!!platformOptions.mergeVirtualHostAttributes).toString() process.env.MERGE_VIRTUAL_HOST_ATTRIBUTES = (!!platformOptions.mergeVirtualHostAttributes).toString()
process.env.UNI_STAT_UNI_CLOUD = '' process.env.UNI_STATISTICS_CONFIG = '""'
process.env.UNI_STAT_DEBUG = '' process.env.UNI_STAT_UNI_CLOUD = '""'
process.env.UNI_STAT_DEBUG = '""'
if ( if (
process.env.UNI_USING_COMPONENTS || process.env.UNI_USING_COMPONENTS ||
process.env.UNI_PLATFORM === 'h5' process.env.UNI_PLATFORM === 'h5'
...@@ -336,9 +337,10 @@ if ( ...@@ -336,9 +337,10 @@ if (
) )
if (uniStatistics.enable === true) { if (uniStatistics.enable === true) {
process.env.UNI_USING_STAT = uniStatistics.version === '2' ? '2' : '1' process.env.UNI_USING_STAT = Number(uniStatistics.version) === 2 ? '2' : '1'
// 获取服务空间配置信息 // 获取服务空间配置信息
const uniCloudConfig = uniStatistics.uniCloud || {} const uniCloudConfig = uniStatistics.uniCloud || {}
process.env.UNI_STATISTICS_CONFIG = JSON.stringify(uniStatistics)
process.env.UNI_STAT_UNI_CLOUD = JSON.stringify(uniCloudConfig) process.env.UNI_STAT_UNI_CLOUD = JSON.stringify(uniCloudConfig)
process.env.UNI_STAT_DEBUG = uniStatistics.debug === true ? 'true' : 'false' process.env.UNI_STAT_DEBUG = uniStatistics.debug === true ? 'true' : 'false'
......
...@@ -431,6 +431,11 @@ module.exports = function (pagesJson, manifestJson, loader) { ...@@ -431,6 +431,11 @@ module.exports = function (pagesJson, manifestJson, loader) {
const qqMapKey = sdkConfigs.maps && sdkConfigs.maps.qqmap && sdkConfigs.maps.qqmap.key const qqMapKey = sdkConfigs.maps && sdkConfigs.maps.qqmap && sdkConfigs.maps.qqmap.key
const googleMapKey = sdkConfigs.maps && sdkConfigs.maps.google && sdkConfigs.maps.google.key const googleMapKey = sdkConfigs.maps && sdkConfigs.maps.google && sdkConfigs.maps.google.key
const aMapKey = sdkConfigs.maps && sdkConfigs.maps.amap && sdkConfigs.maps.amap.key
const aMapSecurityJsCode =
sdkConfigs.maps && sdkConfigs.maps.amap && sdkConfigs.maps.amap.securityJsCode
const aMapServiceHost =
sdkConfigs.maps && sdkConfigs.maps.amap && sdkConfigs.maps.amap.serviceHost
let locale = manifestJson.locale let locale = manifestJson.locale
locale = locale && locale.toUpperCase() !== 'AUTO' ? locale : '' locale = locale && locale.toUpperCase() !== 'AUTO' ? locale : ''
...@@ -456,6 +461,9 @@ global.__uniConfig.networkTimeout = ${JSON.stringify(networkTimeoutConfig)}; ...@@ -456,6 +461,9 @@ global.__uniConfig.networkTimeout = ${JSON.stringify(networkTimeoutConfig)};
global.__uniConfig.sdkConfigs = ${JSON.stringify(sdkConfigs)}; global.__uniConfig.sdkConfigs = ${JSON.stringify(sdkConfigs)};
global.__uniConfig.qqMapKey = ${JSON.stringify(qqMapKey)}; global.__uniConfig.qqMapKey = ${JSON.stringify(qqMapKey)};
global.__uniConfig.googleMapKey = ${JSON.stringify(googleMapKey)}; global.__uniConfig.googleMapKey = ${JSON.stringify(googleMapKey)};
global.__uniConfig.aMapKey = ${JSON.stringify(aMapKey)};
global.__uniConfig.aMapSecurityJsCode = ${JSON.stringify(aMapSecurityJsCode)};
global.__uniConfig.aMapServiceHost = ${JSON.stringify(aMapServiceHost)};
global.__uniConfig.locale = ${JSON.stringify(locale)}; global.__uniConfig.locale = ${JSON.stringify(locale)};
global.__uniConfig.fallbackLocale = ${JSON.stringify(manifestJson.fallbackLocale)}; global.__uniConfig.fallbackLocale = ${JSON.stringify(manifestJson.fallbackLocale)};
global.__uniConfig.locales = locales.keys().reduce((res,key)=>{const locale=key.replace(/\\.\\/(uni-app.)?(.*).json/,'$2');const messages = locales(key);Object.assign(res[locale]||(res[locale]={}),messages.common||messages);return res},{}); global.__uniConfig.locales = locales.keys().reduce((res,key)=>{const locale=key.replace(/\\.\\/(uni-app.)?(.*).json/,'$2');const messages = locales(key);Object.assign(res[locale]||(res[locale]={}),messages.common||messages);return res},{});
......
...@@ -11,5 +11,9 @@ export const scanCode = { ...@@ -11,5 +11,9 @@ export const scanCode = {
sound: { sound: {
type: String, type: String,
default: 'none' default: 'none'
},
autoZoom: {
type: Boolean,
default: true
} }
} }
...@@ -6,6 +6,8 @@ import { ...@@ -6,6 +6,8 @@ import {
showPage showPage
} from '../../../helpers/page.js' } from '../../../helpers/page.js'
import { getLocale } from 'uni-core/helpers/i18n'
function getStatusBarStyle () { function getStatusBarStyle () {
let style = plus.navigator.getStatusBarStyle() let style = plus.navigator.getStatusBarStyle()
if (style === 'UIStatusBarStyleBlackTranslucent' || style === 'UIStatusBarStyleBlackOpaque' || style === 'null') { if (style === 'UIStatusBarStyleBlackTranslucent' || style === 'UIStatusBarStyleBlackOpaque' || style === 'null') {
...@@ -23,7 +25,9 @@ export function chooseLocation (options, callbackId) { ...@@ -23,7 +25,9 @@ export function chooseLocation (options, callbackId) {
let result let result
const page = showPage({ const page = showPage({
url: '__uniappchooselocation', url: '__uniappchooselocation',
data: options, data: Object.assign({}, options, {
locale: getLocale()
}),
style: { style: {
animationType: options.animationType || 'slide-in-bottom', animationType: options.animationType || 'slide-in-bottom',
titleNView: false, titleNView: false,
......
...@@ -6,10 +6,14 @@ import { ...@@ -6,10 +6,14 @@ import {
showPage showPage
} from '../../../helpers/page.js' } from '../../../helpers/page.js'
import { getLocale } from 'uni-core/helpers/i18n'
export function openLocation (data, callbackId) { export function openLocation (data, callbackId) {
showPage({ showPage({
url: '__uniappopenlocation', url: '__uniappopenlocation',
data, data: Object.assign({}, data, {
locale: getLocale()
}),
style: { style: {
titleNView: { titleNView: {
type: 'transparent' type: 'transparent'
......
...@@ -12,15 +12,21 @@ import { NAVBAR_HEIGHT } from 'uni-helpers/constants' ...@@ -12,15 +12,21 @@ import { NAVBAR_HEIGHT } from 'uni-helpers/constants'
let webview = false let webview = false
const insertHTMLWebView = ({ const insertHTMLWebView = ({
webviewStyles,
htmlId, htmlId,
updateTitle updateTitle
}) => { }) => {
const parentWebview = plus.webview.currentWebview() const parentWebview = plus.webview.currentWebview()
// fixed by hxy web-view 组件所在的 webview 不注入 uni-app 框架 // fixed by hxy web-view 组件所在的 webview 不注入 uni-app 框架
const styles = { const styles = Object.assign(
'uni-app': 'none', {
isUniH5: true 'uni-app': 'none',
} isUniH5: true,
// ios 默认绘制到安全区外
contentAdjust: false
},
webviewStyles
)
const parentTitleNView = parentWebview.getTitleNView() const parentTitleNView = parentWebview.getTitleNView()
if (parentTitleNView) { if (parentTitleNView) {
if (plus.navigator.isImmersedStatusbar()) { if (plus.navigator.isImmersedStatusbar()) {
...@@ -100,6 +106,7 @@ export default { ...@@ -100,6 +106,7 @@ export default {
mounted () { mounted () {
this.htmlId = WEBVIEW_ID_PREFIX + this.$page.id this.htmlId = WEBVIEW_ID_PREFIX + this.$page.id
insertHTMLWebView({ insertHTMLWebView({
webviewStyles: this.webviewStyles,
htmlId: this.htmlId, htmlId: this.htmlId,
updateTitle: this.updateTitle updateTitle: this.updateTitle
}) })
......
...@@ -198,7 +198,7 @@ export default { ...@@ -198,7 +198,7 @@ export default {
this.list.push({ this.list.push({
name: item.title, name: item.title,
address: item.address, address: item.address,
distance: item._distance, distance: item._distance || item.distance,
latitude: item.location.lat, latitude: item.location.lat,
longitude: item.location.lng longitude: item.location.lng
}) })
...@@ -265,6 +265,39 @@ export default { ...@@ -265,6 +265,39 @@ export default {
}, () => { }, () => {
this.loading = false this.loading = false
}) })
} else if (mapInfo.type === MapType.AMAP) {
const self = this
window.AMap.plugin('AMap.PlaceSearch', function () {
var autoOptions = {
city: '全国',
pageSize: 10,
pageIndex: self.pageIndex
}
var placeSearch = new window.AMap.PlaceSearch(autoOptions)
if (self.searching) {
placeSearch.searchNearBy(self.keyword, [self.longitude, self.latitude], 50000, function (status, result) {
if (status === 'error') {
console.error(result)
} else if (status === 'no_data') {
self.hasNextPage = false
} else {
self.pushData(result.poiList.pois)
}
})
} else {
placeSearch.searchNearBy('', [self.longitude, self.latitude], 5000, function (status, result) {
if (status === 'error') {
console.error(result)
} else if (status === 'no_data') {
self.hasNextPage = false
} else {
self.pushData(result.poiList.pois)
}
})
}
self.loading = false
})
} }
}, },
loadMore () { loadMore () {
......
...@@ -7,29 +7,29 @@ ...@@ -7,29 +7,29 @@
:markers="[marker, location]" :markers="[marker, location]"
@regionchange="onRegionChange" @regionchange="onRegionChange"
> >
<div <div
class="map-move" class="map-move"
@click="moveToLocation" @click="moveToLocation"
> >
<i>&#xec32;</i> <i>&#xec32;</i>
</div> </div>
</v-uni-map> </v-uni-map>
<div class="info"> <div class="info">
<div <div
class="name" class="name"
@click="setCenter(marker)" @click="setCenter(marker)"
> >
{{ name }} {{ name }}
</div> </div>
<div <div
class="address" class="address"
@click="setCenter(marker)" @click="setCenter(marker)"
> >
{{ address }} {{ address }}
</div> </div>
<div <div
class="nav" class="nav"
@click="nav" @click="nav"
> >
<svg <svg
width="26" width="26"
...@@ -45,9 +45,9 @@ ...@@ -45,9 +45,9 @@
</svg> </svg>
</div> </div>
</div> </div>
<div <div
class="nav-btn-back" class="nav-btn-back"
@click="back" @click="back"
> >
<i class="uni-btn-icon">&#xe601;</i> <i class="uni-btn-icon">&#xe601;</i>
</div> </div>
...@@ -147,6 +147,11 @@ export default { ...@@ -147,6 +147,11 @@ export default {
}%2C${this.longitude}&from=${encodeURIComponent( }%2C${this.longitude}&from=${encodeURIComponent(
'我的位置' '我的位置'
)}&to=${encodeURIComponent(this.name || '目的地')}&ref=${mapInfo.key}` )}&to=${encodeURIComponent(this.name || '目的地')}&ref=${mapInfo.key}`
} else if (mapInfo.type === MapType.AMAP) {
url = `https://m.amap.com/navi/?dest=${this.longitude},${this.latitude}&key=${mapInfo.key}`
if (this.name) {
url += `&destName=${this.name}`
}
} }
window.open(url) window.open(url)
} }
......
...@@ -6,21 +6,35 @@ export const ICON_PATH_TARGET = ...@@ -6,21 +6,35 @@ export const ICON_PATH_TARGET =
export const MapType = { export const MapType = {
QQ: 'qq', QQ: 'qq',
GOOGLE: 'google', GOOGLE: 'google',
AMAP: 'AMap',
UNKNOWN: '' UNKNOWN: ''
} }
export function getMapInfo () { export function getMapInfo () {
let type = MapType.UNKNOWN
let key = ''
if (__uniConfig.qqMapKey) { if (__uniConfig.qqMapKey) {
type = MapType.QQ return {
key = __uniConfig.qqMapKey type: MapType.QQ,
} else if (__uniConfig.googleMapKey) { key: __uniConfig.qqMapKey
type = MapType.GOOGLE }
key = __uniConfig.googleMapKey }
if (__uniConfig.googleMapKey) {
return {
type: MapType.GOOGLE,
key: __uniConfig.googleMapKey
}
}
if (__uniConfig.aMapKey) {
return {
type: MapType.AMAP,
key: __uniConfig.aMapKey,
securityJsCode: __uniConfig.aMapSecurityJsCode,
serviceHost: __uniConfig.aMapServiceHost
}
} }
return { return {
type, type: MapType.UNKNOWN,
key key: ''
} }
} }
export const IS_AMAP = getMapInfo().type === MapType.AMAP
...@@ -67,6 +67,21 @@ export function getLocation ({ ...@@ -67,6 +67,21 @@ export function getLocation ({
reject(new Error('network error')) reject(new Error('network error'))
} }
}) })
} else if (mapInfo.type === MapType.AMAP) {
window.AMap.plugin('AMap.Geolocation', function () {
var geolocation = new window.AMap.Geolocation({})
geolocation.getCurrentPosition(function (status, res) {
if (status === 'complete') {
resolve({
latitude: res.position.lat,
longitude: res.position.lng,
accuracy: res.accuracy
})
} else {
reject(new Error((res.message) || JSON.stringify(res)))
}
})
})
} else { } else {
reject(new Error('network error')) reject(new Error('network error'))
} }
......
<template> <template>
<uni-map <uni-map
:id="id" :id="id"
ref="mapContainer"
v-on="$listeners" v-on="$listeners"
@touchend="handleAMapClick"
> >
<map-marker <map-marker
v-for="item in markers" v-for="item in markers"
...@@ -46,7 +48,17 @@ import { ...@@ -46,7 +48,17 @@ import {
import mapMarker from './map-marker' import mapMarker from './map-marker'
import mapPolygon from './map-polygon' import mapPolygon from './map-polygon'
import { ICON_PATH_ORIGIN } from '../../../helpers/location' import { ICON_PATH_ORIGIN, IS_AMAP } from '../../../helpers/location'
function getAMapPosition (maps, latitude, longitude) {
return new maps.LngLat(longitude, latitude)
}
function getGoogleQQMapPosition (maps, latitude, longitude) {
return new maps.LatLng(latitude, longitude)
}
function getMapPosition (maps, latitude, longitude) {
return IS_AMAP ? getAMapPosition(maps, latitude, longitude) : getGoogleQQMapPosition(maps, latitude, longitude)
}
function getLat (latLng) { function getLat (latLng) {
if ('getLat' in latLng) { if ('getLat' in latLng) {
...@@ -201,6 +213,9 @@ export default { ...@@ -201,6 +213,9 @@ export default {
}, },
mounted () { mounted () {
loadMaps(this.libraries, result => { loadMaps(this.libraries, result => {
// 兼容高德地图
result.event = result.event || result.Event
result.Point = result.Point || result.BuryPoint
this._maps = result this._maps = result
this.init() this.init()
}) })
...@@ -212,6 +227,13 @@ export default { ...@@ -212,6 +227,13 @@ export default {
this.removeLocation() this.removeLocation()
}, },
methods: { methods: {
handleAMapClick (e) {
if (IS_AMAP) {
const { pageX, pageY } = e.changedTouches[0]
this.$trigger('click', { x: pageX, y: pageY }, {})
this.$trigger('tap', { x: pageX, y: pageY }, {})
}
},
_handleSubscribe ({ _handleSubscribe ({
type, type,
data = {} data = {}
...@@ -247,10 +269,14 @@ export default { ...@@ -247,10 +269,14 @@ export default {
case 'moveToLocation': case 'moveToLocation':
{ {
const { latitude, longitude } = data const { latitude, longitude } = data
var locationPosition = (latitude && longitude) ? new maps.LatLng(latitude, longitude) : this._locationPosition const locationPosition = (latitude && longitude) ? getMapPosition(maps, latitude, longitude) : this._locationPosition
if (locationPosition) { if (locationPosition) {
this._map.setCenter(locationPosition) this._map.setCenter(locationPosition)
callback({}) callback({
latitude,
longitude
})
} }
} }
break break
...@@ -267,7 +293,7 @@ export default { ...@@ -267,7 +293,7 @@ export default {
rotation = marker.getRotation() rotation = marker.getRotation()
} }
var a = marker.getPosition() var a = marker.getPosition()
var b = new maps.LatLng(destination.latitude, destination.longitude) const b = getMapPosition(maps, destination.latitude, destination.longitude)
var distance = maps.geometry.spherical.computeDistanceBetween(a, b) / 1000 var distance = maps.geometry.spherical.computeDistanceBetween(a, b) / 1000
var time = ((typeof duration === 'number') ? duration : 1000) / (1000 * 60 * 60) var time = ((typeof duration === 'number') ? duration : 1000) / (1000 * 60 * 60)
var speed = distance / time var speed = distance / time
...@@ -325,20 +351,26 @@ export default { ...@@ -325,20 +351,26 @@ export default {
this.fitBounds(data.points) this.fitBounds(data.points)
break break
case 'getRegion': case 'getRegion':
this.boundsReady(() => { this.mapReady(() => {
var latLngBounds = this._map.getBounds() this.boundsReady(() => {
var southwest = latLngBounds.getSouthWest() const latLngBounds = this._map.getBounds()
var northeast = latLngBounds.getNorthEast() const southwest = latLngBounds.getSouthWest()
callback({ const northeast = latLngBounds.getNorthEast()
southwest: { callback({
latitude: getLat(southwest), southwest: {
longitude: getLng(southwest) latitude: getLat(southwest),
}, longitude: getLng(southwest)
northeast: { },
latitude: getLat(northeast), northeast: {
longitude: getLng(northeast) latitude: getLat(northeast),
} longitude: getLng(northeast)
}
})
}) })
if (IS_AMAP) {
this.isBoundsReady = true
this.$emit('boundsready')
}
}) })
break break
case 'getScale': case 'getScale':
...@@ -352,7 +384,7 @@ export default { ...@@ -352,7 +384,7 @@ export default {
}, },
init () { init () {
const maps = this._maps const maps = this._maps
var center = new maps.LatLng(this.center.latitude, this.center.longitude) const center = getMapPosition(maps, this.center.latitude, this.center.longitude)
var map = this._map = new maps.Map(this.$refs.map, { var map = this._map = new maps.Map(this.$refs.map, {
center, center,
zoom: Number(this.scale), zoom: Number(this.scale),
...@@ -442,7 +474,8 @@ export default { ...@@ -442,7 +474,8 @@ export default {
this.center.longitude = longitude this.center.longitude = longitude
if (this._map) { if (this._map) {
this.mapReady(() => { this.mapReady(() => {
this._map.setCenter(new maps.LatLng(latitude, longitude)) const centerPosition = getMapPosition(maps, latitude, longitude)
this._map.setCenter(centerPosition)
}) })
} }
} }
...@@ -453,10 +486,13 @@ export default { ...@@ -453,10 +486,13 @@ export default {
var polyline = this.polylineSync var polyline = this.polylineSync
this.removePolyline() this.removePolyline()
this.polyline.forEach(option => { this.polyline.forEach(option => {
var path = [] const path = []
option.points.forEach(point => { option.points.forEach(point => {
path.push(new maps.LatLng(point.latitude, point.longitude)) const pointPosition = IS_AMAP ? [point.longitude, point.latitude] : getGoogleQQMapPosition(maps, point.latitude, point.longitude)
path.push(pointPosition)
}) })
const borderWidth = Number(option.borderWidth) || 0 const borderWidth = Number(option.borderWidth) || 0
const { r: sr, g: sg, b: sb, a: sa } = hexToRgba(option.color) const { r: sr, g: sg, b: sb, a: sa } = hexToRgba(option.color)
const { r: br, g: bg, b: bb, a: ba } = hexToRgba(option.borderColor) const { r: br, g: bg, b: bb, a: ba } = hexToRgba(option.borderColor)
...@@ -464,14 +500,23 @@ export default { ...@@ -464,14 +500,23 @@ export default {
map, map,
clickable: false, clickable: false,
path, path,
strokeWeight: option.width + borderWidth, strokeWeight: ((Number(option.width) || 0) + borderWidth) || 6,
strokeDashStyle: option.dottedLine ? 'dash' : 'solid' strokeDashStyle: option.dottedLine ? 'dash' : 'solid'
} }
if (IS_AMAP) {
polylineOptions.strokeColor = option.strokeColor
polylineOptions.strokeStyle = option.dottedLine ? 'dashed' : 'solid'
polylineOptions.isOutline = !!option.borderWidth
polylineOptions.borderWeight = option.borderWidth
polylineOptions.outlineColor = option.borderColor
}
const polylineBorderOptions = { const polylineBorderOptions = {
map, map,
clickable: false, clickable: false,
path, path,
strokeWeight: option.width, strokeWeight: option.width || 6,
strokeDashStyle: option.dottedLine ? 'dash' : 'solid' strokeDashStyle: option.dottedLine ? 'dash' : 'solid'
} }
if ('Color' in maps) { if ('Color' in maps) {
...@@ -486,7 +531,11 @@ export default { ...@@ -486,7 +531,11 @@ export default {
if (borderWidth) { if (borderWidth) {
polyline.push(new maps.Polyline(polylineBorderOptions)) polyline.push(new maps.Polyline(polylineBorderOptions))
} }
polyline.push(new maps.Polyline(polylineOptions)) const _polyline = new maps.Polyline(polylineOptions)
if (IS_AMAP) {
map.add(_polyline)
}
polyline.push(_polyline)
}) })
}, },
removePolyline () { removePolyline () {
...@@ -498,12 +547,11 @@ export default { ...@@ -498,12 +547,11 @@ export default {
}, },
createCircles () { createCircles () {
const maps = this._maps const maps = this._maps
var map = this._map const map = this._map
var circles = this.circlesSync const circles = this.circlesSync
this.removeCircles() this.removeCircles()
this.circles.forEach(option => { this.circles.forEach(option => {
var center = new maps.LatLng(option.latitude, option.longitude) const center = IS_AMAP ? [option.longitude, option.latitude] : getGoogleQQMapPosition(maps, option.latitude, option.longitude)
const circleOptions = { const circleOptions = {
map, map,
center, center,
...@@ -512,18 +560,30 @@ export default { ...@@ -512,18 +560,30 @@ export default {
strokeWeight: Number(option.strokeWidth) || 1, strokeWeight: Number(option.strokeWidth) || 1,
strokeDashStyle: 'solid' strokeDashStyle: 'solid'
} }
const { r: fr, g: fg, b: fb, a: fa } = hexToRgba(option.fillColor || '#00000000')
const { r: sr, g: sg, b: sb, a: sa } = hexToRgba(option.color || '#000000') if (IS_AMAP) {
if ('Color' in maps) { circleOptions.strokeColor = option.color
circleOptions.fillColor = new maps.Color(fr, fg, fb, fa) circleOptions.fillColor = option.fillColor || '#000'
circleOptions.strokeColor = new maps.Color(sr, sg, sb, sa)
} else { } else {
circleOptions.fillColor = `rgb(${fr}, ${fg}, ${fb})` const { r: fr, g: fg, b: fb, a: fa } = hexToRgba(option.fillColor || '#00000000')
circleOptions.fillOpacity = fa const { r: sr, g: sg, b: sb, a: sa } = hexToRgba(option.color || '#000000')
circleOptions.strokeColor = `rgb(${sr}, ${sg}, ${sb})` if ('Color' in maps) {
circleOptions.strokeOpacity = sa // 腾讯
circleOptions.fillColor = new maps.Color(fr, fg, fb, fa)
circleOptions.strokeColor = new maps.Color(sr, sg, sb, sa)
} else {
// Google
circleOptions.fillColor = `rgb(${fr}, ${fg}, ${fb})`
circleOptions.fillOpacity = fa
circleOptions.strokeColor = `rgb(${sr}, ${sg}, ${sb})`
circleOptions.strokeOpacity = sa
}
}
const circle = new maps.Circle(circleOptions)
if (IS_AMAP) {
map.add(circle)
} }
var circle = new maps.Circle(circleOptions)
circles.push(circle) circles.push(circle)
}) })
}, },
...@@ -549,6 +609,8 @@ export default { ...@@ -549,6 +609,8 @@ export default {
style.position = 'absolute' style.position = 'absolute'
style.width = 0 style.width = 0
style.height = 0 style.height = 0
style.top = 0
style.left = 0
img.onload = () => { img.onload = () => {
if (option.position.width) { if (option.position.width) {
img.width = option.position.width img.width = option.position.width
...@@ -569,8 +631,13 @@ export default { ...@@ -569,8 +631,13 @@ export default {
controlId: option.id controlId: option.id
}) })
} }
$event.stopPropagation()
}
if (IS_AMAP) {
this.$refs.mapContainer.appendChild(control)
} else {
map.controls[maps.ControlPosition.TOP_LEFT].push(control)
} }
map.controls[maps.ControlPosition.TOP_LEFT].push(control)
controls.push(control) controls.push(control)
}) })
}, },
...@@ -583,8 +650,8 @@ export default { ...@@ -583,8 +650,8 @@ export default {
}, },
createLocation () { createLocation () {
const maps = this._maps const maps = this._maps
var map = this._map const map = this._map
var location = this._location let location = this._location
if (location) { if (location) {
this.removeLocation() this.removeLocation()
} }
...@@ -594,14 +661,30 @@ export default { ...@@ -594,14 +661,30 @@ export default {
if (location !== this._location) { if (location !== this._location) {
return return
} }
var position = new maps.LatLng(res.latitude, res.longitude) const position = getMapPosition(maps, res.latitude, res.longitude)
location = new maps.Marker({ if (IS_AMAP) {
position, location = new maps.Marker({
map, position,
icon: new maps.MarkerImage(ICON_PATH_ORIGIN, null, null, new maps.Point(22, 22), new maps.Size(44, 44)), map,
flat: true, flat: true,
rotation: 0 rotation: 0
}) })
const icon = new maps.Icon({
size: new maps.Size(44, 44),
image: ICON_PATH_ORIGIN,
imageSize: new maps.Size(44, 44)
})
location.setIcon(icon)
map.add(location)
} else {
location = new maps.Marker({
position,
map,
icon: new maps.MarkerImage(ICON_PATH_ORIGIN, null, null, new maps.Point(22, 22), new maps.Size(44, 44)),
flat: true,
rotation: 0
})
}
this._location = location this._location = location
refreshLocation() refreshLocation()
this.__onCompassChange = function (res) { this.__onCompassChange = function (res) {
...@@ -623,7 +706,7 @@ export default { ...@@ -623,7 +706,7 @@ export default {
uni.getLocation({ uni.getLocation({
type: 'gcj02', type: 'gcj02',
success: (res) => { success: (res) => {
var locationPosition = self._locationPosition = new maps.LatLng(res.latitude, res.longitude) const locationPosition = self._locationPosition = getMapPosition(maps, res.latitude, res.longitude)
location.setPosition(locationPosition) location.setPosition(locationPosition)
}, },
fail: e => { fail: e => {
...@@ -648,20 +731,35 @@ export default { ...@@ -648,20 +731,35 @@ export default {
fitBounds (points, cb) { fitBounds (points, cb) {
const maps = this._maps const maps = this._maps
this.boundsReady(() => { this.boundsReady(() => {
var map = this._map const map = this._map
var bounds = new maps.LatLngBounds()
if (IS_AMAP) {
const _points = []
points.forEach(point => {
_points.push([point.longitude, point.latitude])
})
const bounds = new maps.Bounds(..._points)
map.setBounds(bounds)
} else {
const bounds = new maps.LatLngBounds()
points.forEach(point => {
const longitude = point.longitude
const latitude = point.latitude
const latLng = getGoogleQQMapPosition(maps, latitude, longitude)
bounds.extend(latLng)
})
map.fitBounds(bounds)
}
points.forEach(point => {
var longitude = point.longitude
var latitude = point.latitude
var latLng = new maps.LatLng(latitude, longitude)
bounds.extend(latLng)
})
map.fitBounds(bounds)
if (typeof cb === 'function') { if (typeof cb === 'function') {
cb() cb()
} }
}) })
if (IS_AMAP) {
this.isBoundsReady = true
this.$emit('boundsready')
}
}, },
mapReady (cb) { mapReady (cb) {
if (this.isMapReady) { if (this.isMapReady) {
...@@ -703,4 +801,16 @@ export default { ...@@ -703,4 +801,16 @@ export default {
uni-map[hidden] { uni-map[hidden] {
display: none; display: none;
} }
/* 处理高德地图 marker label 默认样式 */
.amap-marker-label{
padding:0;
border:none;
background-color: transparent;
}
/* 处理高德地图 open-location icon 被遮挡问题 */
.amap-marker>.amap-icon>img{
left:0!important;
top:0!important;
}
</style> </style>
import { mapInfo, MapType, IS_AMAP } from '../../../helpers/location'
import getRealPath from 'uni-platform/helpers/get-real-path' import getRealPath from 'uni-platform/helpers/get-real-path'
export default { export default {
...@@ -97,26 +98,34 @@ export default { ...@@ -97,26 +98,34 @@ export default {
this.updateMarker(props) this.updateMarker(props)
maps.event.addListener(marker, 'click', (e) => { maps.event.addListener(marker, 'click', (e) => {
const callout = marker.callout const callout = marker.callout
if (callout) { if (callout && !callout.alwaysVisible) {
const div = callout.div if (IS_AMAP) {
const parent = div.parentNode callout.visible = !callout.visible
if (!callout.alwaysVisible) { if (callout.visible) {
marker.callout.createAMapText()
} else {
marker.callout.removeAMapText()
}
} else {
callout.set('visible', !callout.visible) callout.set('visible', !callout.visible)
} if (callout.visible) {
if (callout.visible) { const div = callout.div
parent.removeChild(div) const parent = div.parentNode
parent.appendChild(div) parent.removeChild(div)
parent.appendChild(div)
}
} }
} }
if (this.idString) { if (this.idString) {
const { latitude, longitude } = this.getMarkerLatitudeLongitude(e)
this.$parent.$trigger('markertap', {}, { this.$parent.$trigger('markertap', {}, {
markerId: Number(this.idString), markerId: Number(this.idString),
latitude: typeof e.latLng.lat === 'function' ? e.latLng.lat() : e.latLng.lat, latitude,
longitude: typeof e.latLng.lat === 'function' ? e.latLng.lng() : e.latLng.lng longitude
}) })
} }
const event = e.event || e.domEvent const event = e.event || e.domEvent || e.originEvent
event.stopPropagation() event.stopPropagation()
}) })
}, },
...@@ -125,7 +134,7 @@ export default { ...@@ -125,7 +134,7 @@ export default {
const maps = this._maps const maps = this._maps
const marker = this._marker const marker = this._marker
const title = option.title const title = option.title
const position = new maps.LatLng(option.latitude, option.longitude) const position = IS_AMAP ? new maps.LngLat(option.longitude, option.latitude) : new maps.LatLng(option.latitude, option.longitude)
const img = new Image() const img = new Image()
img.onload = () => { img.onload = () => {
const anchor = option.anchor || {} const anchor = option.anchor || {}
...@@ -143,6 +152,7 @@ export default { ...@@ -143,6 +152,7 @@ export default {
} }
const top = h - (h - y * h) const top = h - (h - y * h)
if ('MarkerImage' in maps) { if ('MarkerImage' in maps) {
// 腾讯 & google
icon = new maps.MarkerImage( icon = new maps.MarkerImage(
img.src, img.src,
null, null,
...@@ -150,6 +160,14 @@ export default { ...@@ -150,6 +160,14 @@ export default {
new maps.Point(x * w, y * h), new maps.Point(x * w, y * h),
new maps.Size(w, h) new maps.Size(w, h)
) )
} else if ('Icon' in maps) {
// 高德
icon = new maps.Icon({
image: img.src,
size: new maps.Size(w, h),
imageSize: new maps.Size(w, h),
imageOffset: new maps.Pixel(x * w, y * h)
})
} else { } else {
icon = { icon = {
url: img.src, url: img.src,
...@@ -182,8 +200,9 @@ export default { ...@@ -182,8 +200,9 @@ export default {
marginTop: (Number(labelOpt.anchorY || labelOpt.y) || 0) + 'px' marginTop: (Number(labelOpt.anchorY || labelOpt.y) || 0) + 'px'
} }
if ('Label' in maps) { if ('Label' in maps) {
// 腾讯
label = new maps.Label({ label = new maps.Label({
position: position, position,
map: map, map: map,
clickable: false, clickable: false,
content: labelOpt.content, content: labelOpt.content,
...@@ -191,13 +210,35 @@ export default { ...@@ -191,13 +210,35 @@ export default {
}) })
marker.label = label marker.label = label
} else if ('setLabel' in marker) { } else if ('setLabel' in marker) {
const className = this.updateMarkerLabelStyle(this.idString, labelStyle) if (IS_AMAP) {
marker.setLabel({ const content =
text: labelOpt.content, `<div style="
color: labelStyle.color, margin-left:${labelStyle.marginLeft};
fontSize: labelStyle.fontSize, margin-top:${labelStyle.marginTop};
className padding:${labelStyle.padding};
}) background-color:${labelStyle.backgroundColor};
border-radius:${labelStyle.borderRadius};
line-height:${labelStyle.lineHeight};
color:${labelStyle.color};
font-size:${labelStyle.fontSize};
">
${labelOpt.content}
<div>`
marker.setLabel({
content,
direction: 'bottom-right'
})
} else {
// google
const className = this.updateMarkerLabelStyle(this.idString, labelStyle)
marker.setLabel({
text: labelOpt.content,
color: labelStyle.color,
fontSize: labelStyle.fontSize,
className
})
}
} }
} }
const calloutOpt = option.callout || {} const calloutOpt = option.callout || {}
...@@ -210,6 +251,8 @@ export default { ...@@ -210,6 +251,8 @@ export default {
position, position,
map, map,
top, top,
// handle AMap callout offset
offsetY: -option.height / 2,
content: calloutOpt.content, content: calloutOpt.content,
color: calloutOpt.color, color: calloutOpt.color,
fontSize: calloutOpt.fontSize, fontSize: calloutOpt.fontSize,
...@@ -223,26 +266,38 @@ export default { ...@@ -223,26 +266,38 @@ export default {
position, position,
map, map,
top, top,
offsetY: -option.height / 2,
content: title, content: title,
boxShadow: boxShadow boxShadow: boxShadow
} }
if (callout) { if (callout) {
callout.setOption(calloutStyle) callout.setOption(calloutStyle)
} else { } else {
callout = marker.callout = new maps.Callout(calloutStyle) if (IS_AMAP) {
callout.div.onclick = ($event) => { const callback = (self) => {
if (this.idString) { if (self.idString) {
this.$parent.$trigger('callouttap', $event, { self.$parent.$trigger('callouttap', {}, {
markerId: Number(this.idString) markerId: Number(self.idString)
}) })
}
}
callout = marker.callout = new maps.Callout(calloutStyle, callback, this)
} else {
callout = marker.callout = new maps.Callout(calloutStyle)
callout.div.onclick = ($event) => {
if (this.idString) {
this.$parent.$trigger('callouttap', $event, {
markerId: Number(this.idString)
})
}
$event.stopPropagation()
$event.preventDefault()
} }
$event.stopPropagation()
$event.preventDefault()
} }
} }
} else { } else {
if (callout) { if (callout) {
callout.setMap(null) this.removeMarkerCallout(marker.callout)
delete marker.callout delete marker.callout
} }
} }
...@@ -276,6 +331,22 @@ export default { ...@@ -276,6 +331,22 @@ export default {
styleEl.innerText = `.${className}{${div.getAttribute('style')}}` styleEl.innerText = `.${className}{${div.getAttribute('style')}}`
return className return className
}, },
getMarkerLatitudeLongitude (e) {
let latitude
let longitude
if (IS_AMAP) {
latitude = e.lnglat.lat
longitude = e.lnglat.lng
} else if (mapInfo.type === MapType.QQ) {
latitude = e.latLng.lat
longitude = e.latLng.lng
} else if (mapInfo.type === MapType.GOOGLE) {
latitude = e.latLng.lat()
longitude = e.latLng.lng()
}
return { latitude, longitude }
},
removeMarker () { removeMarker () {
const marker = this._marker const marker = this._marker
if (marker) { if (marker) {
...@@ -283,12 +354,19 @@ export default { ...@@ -283,12 +354,19 @@ export default {
marker.label.setMap(null) marker.label.setMap(null)
} }
if (marker.callout) { if (marker.callout) {
marker.callout.setMap(null) this.removeMarkerCallout(marker.callout)
} }
marker.setMap(null) marker.setMap(null)
} }
delete this.$parent._markers[this.idString] delete this.$parent._markers[this.idString]
this._marker = null this._marker = null
},
removeMarkerCallout (callout) {
if (IS_AMAP) {
callout.removeAMapText()
} else {
callout.setMap(null)
}
} }
}, },
render () { render () {
......
import { hexToRgba } from 'uni-shared' import { hexToRgba } from 'uni-shared'
import { IS_AMAP } from '../../../helpers/location'
export default { export default {
props: { props: {
// 边框虚线,腾讯地图支持,google 地图不支持,默认值为[0, 0] 为实线,非 [0, 0] 为虚线,H5 端无法像微信小程序一样控制虚线的间隔像素大小 // 边框虚线,腾讯地图支持,google 高德 地图不支持,默认值为[0, 0] 为实线,非 [0, 0] 为虚线,H5 端无法像微信小程序一样控制虚线的间隔像素大小
dashArray: { dashArray: {
type: Array, type: Array,
default: () => [0, 0] default: () => [0, 0]
...@@ -65,7 +66,7 @@ export default { ...@@ -65,7 +66,7 @@ export default {
const path = points.map(item => { const path = points.map(item => {
const { latitude, longitude } = item const { latitude, longitude } = item
return new _maps.LatLng(latitude, longitude) return IS_AMAP ? [longitude, latitude] : new _maps.LatLng(latitude, longitude)
}) })
const { r: fcR, g: fcG, b: fcB, a: fcA } = hexToRgba(fillColor) const { r: fcR, g: fcG, b: fcB, a: fcA } = hexToRgba(fillColor)
......
import { IS_AMAP } from '../../../../helpers/location'
export function createCallout (maps) { export function createCallout (maps) {
const overlay = new (maps.OverlayView || maps.Overlay)()
function onAdd () { function onAdd () {
const div = this.div const div = this.div
const panes = this.getPanes() const panes = this.getPanes()
...@@ -12,6 +13,40 @@ export function createCallout (maps) { ...@@ -12,6 +13,40 @@ export function createCallout (maps) {
} }
} }
function createAMapText () {
const option = this.option
this.Text = new maps.Text({
text: option.content,
anchor: 'bottom-center', // 设置文本标记锚点
offset: new maps.Pixel(0, option.offsetY),
style: {
'margin-bottom': '1rem',
padding: (option.padding || 8) + 'px',
'line-height': (option.fontSize || 14) + 'px',
'border-radius': (option.borderRadius || 0) + 'px',
'border-color': `${option.bgColor || '#fff'} transparent transparent`,
'background-color': option.bgColor || '#fff',
'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
'text-align': 'center',
'font-size': (option.fontSize || 14) + 'px',
color: option.color || '#000'
},
position: option.position
})
maps.event.addListener(this.Text, 'click', () => {
this.callback(this.parent)
})
this.Text.setMap(option.map)
}
function removeAMapText () {
if (this.Text) {
this.option.map.remove(this.Text)
}
}
class Callout { class Callout {
option option
position position
...@@ -20,6 +55,9 @@ export function createCallout (maps) { ...@@ -20,6 +55,9 @@ export function createCallout (maps) {
alwaysVisible alwaysVisible
div div
triangle triangle
callback
parent
Text
set onclick (callback) { set onclick (callback) {
this.div.onclick = callback this.div.onclick = callback
...@@ -29,43 +67,60 @@ export function createCallout (maps) { ...@@ -29,43 +67,60 @@ export function createCallout (maps) {
return this.div.onclick return this.div.onclick
} }
constructor (option = {}) { constructor (option = {}, callback, parent) {
this.option = option || {} this.option = option || {}
const map = option.map this.visible = this.alwaysVisible = option.display === 'ALWAYS'
this.position = option.position if (IS_AMAP) {
this.index = 1 this.callback = callback
const visible = (this.visible = this.alwaysVisible = option.display === 'ALWAYS') this.parent = parent
const div = (this.div = document.createElement('div')) if (this.visible) {
const divStyle = div.style this.createAMapText()
divStyle.position = 'absolute' }
divStyle.whiteSpace = 'nowrap' } else {
divStyle.transform = 'translateX(-50%) translateY(-100%)' const map = option.map
divStyle.zIndex = '1' this.position = option.position
divStyle.boxShadow = option.boxShadow || 'none' this.index = 1
divStyle.display = visible ? 'block' : 'none' const div = (this.div = document.createElement('div'))
const triangle = (this.triangle = document.createElement('div')) const divStyle = div.style
triangle.setAttribute( divStyle.position = 'absolute'
'style', divStyle.whiteSpace = 'nowrap'
'position: absolute;white-space: nowrap;border-width: 4px;border-style: solid;border-color: #fff transparent transparent;border-image: initial;font-size: 12px;padding: 0px;background-color: transparent;width: 0px;height: 0px;transform: translate(-50%, 100%);left: 50%;bottom: 0;' divStyle.transform = 'translateX(-50%) translateY(-100%)'
) divStyle.zIndex = '1'
this.setStyle(option) divStyle.boxShadow = option.boxShadow || 'none'
div.appendChild(triangle) divStyle.display = this.visible ? 'block' : 'none'
if (map) { const triangle = (this.triangle = document.createElement('div'))
this.setMap(map) triangle.setAttribute(
'style',
'position: absolute;white-space: nowrap;border-width: 4px;border-style: solid;border-color: #fff transparent transparent;border-image: initial;font-size: 12px;padding: 0px;background-color: transparent;width: 0px;height: 0px;transform: translate(-50%, 100%);left: 50%;bottom: 0;'
)
this.setStyle(option)
div.appendChild(triangle)
if (map) {
this.setMap(map)
}
} }
} }
createAMapText = createAMapText
removeAMapText = removeAMapText
onAdd = onAdd onAdd = onAdd
construct = onAdd construct = onAdd
setOption (option) { setOption (option) {
this.option = option this.option = option
this.setPosition(option.position)
if (option.display === 'ALWAYS') { if (option.display === 'ALWAYS') {
this.alwaysVisible = this.visible = true this.alwaysVisible = this.visible = true
} else { } else {
this.alwaysVisible = false this.alwaysVisible = false
} }
this.setStyle(option) if (IS_AMAP) {
if (this.visible) {
this.createAMapText()
}
} else {
this.setPosition(option.position)
this.setStyle(option)
}
} }
setStyle (option) { setStyle (option) {
...@@ -107,11 +162,15 @@ export function createCallout (maps) { ...@@ -107,11 +162,15 @@ export function createCallout (maps) {
destroy = onRemove destroy = onRemove
} }
const prototype = Callout.prototype if (!IS_AMAP) {
for (const key in overlay) { const prototype = Callout.prototype
if (!(key in prototype)) { const overlay = new (maps.OverlayView || maps.Overlay)()
prototype[key] = overlay[key] for (const key in overlay) {
if (!(key in prototype)) {
prototype[key] = overlay[key]
}
} }
} }
return Callout return Callout
} }
import { import {
MapType, MapType,
getMapInfo getMapInfo,
IS_AMAP
} from '../../../../helpers/location' } from '../../../../helpers/location'
import { createCallout } from './callout' import { createCallout } from './callout'
...@@ -21,7 +22,7 @@ export function loadMaps (libraries, callback) { ...@@ -21,7 +22,7 @@ export function loadMaps (libraries, callback) {
window[mapInfo.type] && window[mapInfo.type] &&
window[mapInfo.type].maps window[mapInfo.type].maps
) { ) {
maps = window[mapInfo.type].maps maps = IS_AMAP ? window[mapInfo.type] : window[mapInfo.type].maps
maps.Callout = maps.Callout || createCallout(maps) maps.Callout = maps.Callout || createCallout(maps)
callback(maps) callback(maps)
} else if (callbacks.length) { } else if (callbacks.length) {
...@@ -32,20 +33,24 @@ export function loadMaps (libraries, callback) { ...@@ -32,20 +33,24 @@ export function loadMaps (libraries, callback) {
const callbackName = GOOGLE_MAP_CALLBACKNAME + mapInfo.type const callbackName = GOOGLE_MAP_CALLBACKNAME + mapInfo.type
globalExt[callbackName] = function () { globalExt[callbackName] = function () {
delete globalExt[callbackName] delete globalExt[callbackName]
maps = window[mapInfo.type].maps maps = IS_AMAP ? window[mapInfo.type] : window[mapInfo.type].maps
maps.Callout = createCallout(maps) maps.Callout = createCallout(maps)
callbacks.forEach((callback) => callback(maps)) callbacks.forEach((callback) => callback(maps))
callbacks.length = 0 callbacks.length = 0
} }
const script = document.createElement('script') const script = document.createElement('script')
let src = let src = getScriptBaseUrl(mapInfo.type)
mapInfo.type === MapType.GOOGLE ? 'https://maps.googleapis.com/maps/api/js?' : 'https://map.qq.com/api/js?v=2.exp&'
if (mapInfo.type === MapType.QQ) { if (mapInfo.type === MapType.QQ) {
libraries.push('geometry') libraries.push('geometry')
} }
if (libraries.length) { if (libraries.length) {
src += `libraries=${libraries.join('%2C')}&` src += `libraries=${libraries.join('%2C')}&`
} }
if (IS_AMAP) {
handleAMapSecurityPolicy(mapInfo)
}
script.src = `${src}key=${mapInfo.key}&callback=${callbackName}` script.src = `${src}key=${mapInfo.key}&callback=${callbackName}`
script.onerror = function () { script.onerror = function () {
console.error('Map load failed.') console.error('Map load failed.')
...@@ -53,3 +58,20 @@ export function loadMaps (libraries, callback) { ...@@ -53,3 +58,20 @@ export function loadMaps (libraries, callback) {
document.body.appendChild(script) document.body.appendChild(script)
} }
} }
function getScriptBaseUrl (mapType) {
const urlMap = {
qq: 'https://map.qq.com/api/js?v=2.exp&',
google: 'https://maps.googleapis.com/maps/api/js?',
AMap: 'https://webapi.amap.com/maps?v=2.0&'
}
return urlMap[mapType]
}
function handleAMapSecurityPolicy (mapInfo) {
window._AMapSecurityConfig = {
securityJsCode: mapInfo.securityJsCode || '',
serviceHost: mapInfo.serviceHost || ''
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册