addressComponent.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. throw new Error('定位失败');
  37. }
  38. }catch(err){
  39. throw new Error(err);
  40. }
  41. }
  42. //搜索地址
  43. async searchPlace(keyword, cityName){
  44. try{
  45. const resObj = await this.fetch('http://apis.map.qq.com/ws/place/v1/search', {
  46. key: this.key,
  47. keyword: encodeURIComponent(keyword),
  48. boundary: 'region(' + encodeURIComponent(cityName) + ',0)',
  49. page_size: 10,
  50. });
  51. if (resObj.status == 0) {
  52. return resObj
  53. }else{
  54. throw new Error('搜索位置信息失败');
  55. }
  56. }catch(err){
  57. throw new Error(err);
  58. }
  59. }
  60. }
  61. export default AddressComponent