index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const service = require('./service/index.js');
  2. class UniMap {
  3. // 构造函数
  4. constructor(data = {}) {
  5. let {
  6. provider, // 平台 weixin-mp 微信小程序 weixin-h5 微信公众号
  7. key, // 密钥
  8. needOriginalResult = false, // 是否需要返回原始信息,默认false
  9. } = data;
  10. let runService = service[provider];
  11. if (!runService) {
  12. throw new Error(`不支持平台:${provider}`);
  13. }
  14. this.service = new runService({
  15. provider,
  16. key,
  17. needOriginalResult
  18. });
  19. //return this.service;
  20. }
  21. // API - 逆地址解析(坐标转地址)
  22. async location2address(data = {}) {
  23. let res = await this._call("location2address", data);
  24. return res;
  25. }
  26. // API - 地址解析(地址转坐标)
  27. async address2location(data = {}) {
  28. let res = await this._call("address2location", data);
  29. return res;
  30. }
  31. // API - 坐标转换
  32. async translate(data = {}) {
  33. let res = await this._call("translate", data);
  34. return res;
  35. }
  36. // API - IP定位
  37. async ip2location(data = {}) {
  38. let res = await this._call("ip2location", data);
  39. return res;
  40. }
  41. // API - 关键词输入提示
  42. async inputtips(data = {}) {
  43. let res = await this._call("inputtips", data);
  44. return res;
  45. }
  46. // API - 周边搜索
  47. async search(data = {}) {
  48. let res = await this._call("search", data);
  49. return res;
  50. }
  51. // API - 行政区划
  52. async districtSearch(data = {}) {
  53. let res = await this._call("districtSearch", data);
  54. return res;
  55. }
  56. // API - 路线规划(驾车/步行/骑行/电动车/公交)
  57. async route(data = {}) {
  58. let urlObj = {
  59. "driving": "drivingRoute",
  60. "walking": "walkingRoute",
  61. "bicycling": "bicyclingRoute",
  62. "ebicycling": "ebicyclingRoute",
  63. "transit": "transitRoute"
  64. };
  65. let res = await this._call(urlObj[data.mode], data);
  66. res.result.mode = data.mode;
  67. return res;
  68. }
  69. // 私有函数
  70. async _call(name, data = {}) {
  71. let runFunction = this.service[name];
  72. if (!runFunction) {
  73. throw new Error(`平台:${this.service.config.provider} 不支持API:${name}`);
  74. }
  75. let res = await runFunction.call(this.service, data); // 此处需要使用call,防止里面的this作用域被意外改变
  76. if (!this.service.config.needOriginalResult) {
  77. delete res.originalResult;
  78. }
  79. //res = JSON.parse(JSON.stringify(res));
  80. return {
  81. provider: this.service.config.provider,
  82. ...res
  83. };
  84. }
  85. }
  86. module.exports = UniMap;