addressComponent.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. 'use strict';
  2. import BaseComponent from './baseComponent'
  3. /*
  4. 腾讯地图API统一调配组件
  5. */
  6. class AddressComponent extends BaseComponent {
  7. constructor(){
  8. super();
  9. this.key = 'RLHBZ-WMPRP-Q3JDS-V2IQA-JNRFH-EJBHL';
  10. }
  11. //获取定位地址
  12. async guessPosition(req){
  13. let ip = req.headers['x-forwarded-for'] ||
  14. req.connection.remoteAddress ||
  15. req.socket.remoteAddress ||
  16. req.connection.socket.remoteAddress;
  17. const ipArr = ip.split(':');
  18. ip = ipArr[ipArr.length -1];
  19. if (process.env.NODE_ENV == 'development') {
  20. ip = '116.231.55.195';
  21. }
  22. try{
  23. const result = await this.fetch('http://apis.map.qq.com/ws/location/v1/ip', {
  24. ip,
  25. key: this.key,
  26. })
  27. if (result.status == 0) {
  28. const cityInfo = {
  29. lat: result.result.location.lat,
  30. lng: result.result.location.lng,
  31. city: result.result.ad_info.city,
  32. }
  33. cityInfo.city = cityInfo.city.replace(/市$/, '');
  34. return cityInfo
  35. }else{
  36. console.log('定位失败');
  37. throw new Error('定位失败');
  38. }
  39. }catch(err){
  40. throw new Error(err);
  41. }
  42. }
  43. //搜索地址
  44. async searchPlace(keyword, cityName){
  45. try{
  46. const resObj = await this.fetch('http://apis.map.qq.com/ws/place/v1/search', {
  47. key: this.key,
  48. keyword: encodeURIComponent(keyword),
  49. boundary: 'region(' + encodeURIComponent(cityName) + ',0)',
  50. page_size: 10,
  51. });
  52. if (resObj.status == 0) {
  53. return resObj
  54. }else{
  55. console.log('搜索位置信息失败')
  56. throw new Error('搜索位置信息失败');
  57. }
  58. }catch(err){
  59. throw new Error(err);
  60. }
  61. }
  62. //测量距离
  63. async getDistance(from, to){
  64. try{
  65. const res = await this.fetch('http://apis.map.qq.com/ws/distance/v1/', {
  66. key: this.key,
  67. from,
  68. to,
  69. })
  70. return res
  71. }catch(err){
  72. console.log('获取位置距离失败')
  73. throw new Error('获取位置距离失败');
  74. }
  75. }
  76. }
  77. export default AddressComponent