vue集成高德地图API工具类封装

import axios, { AxiosInstance, AxiosResponse } from 'axios';// 高德地图 API 响应基础结构
interface AMapResponse {status: string;info: string;infocode: string;
}// 逆地理编码响应结构
interface RegeoResponse extends AMapResponse {regeocode: {formatted_address: string;addressComponent: {province: string;city: string;district: string;township: string;citycode: string;adcode: string;};pois?: Array<{ id: string; name: string; address: string }>;roads?: Array<{ id: string; name: string }>;roadinters?: Array<{ direction: string; distance: string }>;};
}// 地理编码响应结构
interface GeoResponse extends AMapResponse {geocodes: Array<{location: string;formatted_address: string;level: string;city: string;district: string;adcode: string;}>;
}// POI 搜索响应结构
interface POISearchResponse extends AMapResponse {pois: Array<{id: string;name: string;type: string;typecode: string;address: string;location: string;pname: string;cityname: string;adname: string;}>;
}// 输入提示响应结构
interface InputTipsResponse extends AMapResponse {tips: Array<{id: string;name: string;district: string;location: string;}>;
}// 距离计算响应结构
interface DistanceResponse extends AMapResponse {results: Array<{distance: string;duration: string;}>;
}// 工具类配置接口
interface AMapConfig {apiKey: string;baseUrl?: string;
}// 逆地理编码选项
interface RegeoOptions {radius?: number;extensions?: 'base' | 'all';poiType?: string;roadLevel?: number;batch?: boolean;
}// POI 搜索选项
interface POISearchOptions {page?: number;offset?: number;extensions?: 'base' | 'all';types?: string;
}class AMapService {private axiosInstance: AxiosInstance;private apiKey: string;private baseUrl: string;/*** 构造函数* @param config - 配置对象,包含 API Key 和可选的基础 URL*/constructor(config: AMapConfig) {this.apiKey = config.apiKey;this.baseUrl = config.baseUrl || 'https://restapi.amap.com/v3';// 初始化 Axios 实例this.axiosInstance = axios.create({baseURL: this.baseUrl,timeout: 10000,headers: {'Content-Type': 'application/json',},});}/*** 发起通用请求* @param endpoint - API 端点* @param params - 请求参数* @returns 请求结果* @private*/private async _request<T>(endpoint: string, params: Record<string, any> = {}): Promise<T> {const baseParams = {key: this.apiKey,output: 'JSON',};// 合并参数并移除空值const queryParams = { ...baseParams, ...params };Object.keys(queryParams).forEach((key) => {if (queryParams[key] === undefined || queryParams[key] === null) {delete queryParams[key];}});try {const response: AxiosResponse<T> = await this.axiosInstance.get(endpoint, { params: queryParams });const data = response.data;if (data.status !== '1') {throw new Error(`高德API错误: ${data.info} (错误码: ${data.infocode})`);}return data;} catch (error) {console.error(`高德地图请求失败 (${endpoint}):`, error);throw error;}}/*** 逆地理编码 - 根据经纬度获取地址信息* @param longitude - 经度* @param latitude - 纬度* @param options - 额外选项* @returns 地址信息*/async regeoCode(longitude: number, latitude: number, options: RegeoOptions = {}): Promise<{province: string;city: string;district: string;township: string;citycode: string;adcode: string;formattedAddress: string;pois: Array<{ id: string; name: string; address: string }>;roads: Array<{ id: string; name: string }>;roadinters: Array<{ direction: string; distance: string }>;rawData: RegeoResponse;}> {const params = {location: `${longitude},${latitude}`,radius: options.radius || 1000,extensions: options.extensions || 'base',poitype: options.poiType,roadlevel: options.roadLevel || 0,batch: options.batch || false,};const data = await this._request<RegeoResponse>('geocode/regeo', params);if (data.regeocode) {const addressComponent = data.regeocode.addressComponent;return {province: addressComponent.province,city: addressComponent.city || addressComponent.province, // 处理直辖市district: addressComponent.district,township: addressComponent.township,citycode: addressComponent.citycode,adcode: addressComponent.adcode,formattedAddress: data.regeocode.formatted_address,pois: data.regeocode.pois || [],roads: data.regeocode.roads || [],roadinters: data.regeocode.roadinters || [],rawData: data,};}throw new Error('未找到地址信息');}/*** 地理编码 - 根据地址描述获取经纬度* @param address - 地址描述* @param city - 城市限定(可选)* @returns 经纬度信息*/async geoCode(address: string, city: string | null = null): Promise<{longitude: number;latitude: number;formattedAddress: string;level: string;city: string;district: string;adcode: string;rawData: GeoResponse['geocodes'][0];}> {const params = { address, city };const data = await this._request<GeoResponse>('geocode/geo', params);if (data.geocodes && data.geocodes.length > 0) {const geocode = data.geocodes[0];const [longitude, latitude] = geocode.location.split(',').map(Number);return {longitude,latitude,formattedAddress: geocode.formatted_address,level: geocode.level,city: geocode.city,district: geocode.district,adcode: geocode.adcode,rawData: geocode,};}throw new Error('未找到对应的地理位置');}/*** 关键字搜索 POI(兴趣点)* @param keywords - 关键字* @param city - 城市限定* @param options - 额外选项* @returns POI 列表*/async searchPOI(keywords: string, city: string | null = null, options: POISearchOptions = {}): Promise<Array<{id: string;name: string;type: string;typecode: string;address: string;location: { longitude: number; latitude: number };pname: string;cityname: string;adname: string;rawData: POISearchResponse['pois'][0];}>> {const params = {keywords,city: city || '全国',page: options.page || 1,offset: options.offset || 20,extensions: options.extensions || 'base',types: options.types,};const data = await this._request<POISearchResponse>('place/text', params);if (data.pois && data.pois.length > 0) {return data.pois.map((poi) => ({id: poi.id,name: poi.name,type: poi.type,typecode: poi.typecode,address: poi.address,location: {longitude: parseFloat(poi.location.split(',')[0]),latitude: parseFloat(poi.location.split(',')[1]),},pname: poi.pname,cityname: poi.cityname,adname: poi.adname,rawData: poi,}));}return [];}/*** 输入提示(自动完成)* @param keywords - 关键词* @param city - 城市限定* @returns 提示列表*/async inputTips(keywords: string, city: string | null = null): Promise<Array<{id: string;name: string;district: string;location: string;}>> {const params = {keywords,city: city || '全国',type: 'all',};const data = await this._request<InputTipsResponse>('assistant/inputtips', params);return data.tips || [];}/*** 批量逆地理编码(最多 20 个点)* @param locations - 经纬度数组 [{longitude, latitude}, ...]* @returns 批量结果*/async batchRegeoCode(locations: Array<{ longitude: number; latitude: number }>): Promise<RegeoResponse['regeocode'][]> {if (!Array.isArray(locations) || locations.length === 0) {throw new Error('位置数组不能为空');}if (locations.length > 20) {throw new Error('批量查询最多支持 20 个点');}const locationStr = locations.map((loc) => `${loc.longitude},${loc.latitude}`).join('|');const data = await this._request<RegeoResponse>('geocode/regeo', {location: locationStr,batch: true,});return data.regeocodes || [];}/*** 计算两点间距离* @param lng1 - 起点经度* @param lat1 - 起点纬度* @param lng2 - 终点经度* @param lat2 - 终点纬度* @returns 距离信息(米)*/async calculateDistance(lng1: number, lat1: number, lng2: number, lat2: number): Promise<{distance: number;duration: number;}> {const data = await this._request<DistanceResponse>('distance', {origins: `${lng1},${lat1}`,destination: `${lng2},${lat2}`,type: 1, // 直线距离});if (data.results && data.results.length > 0) {return {distance: parseInt(data.results[0].distance),duration: parseInt(data.results[0].duration),};}throw new Error('距离计算失败');}
}// 单例模式
let amapInstance: AMapService | null = null;/*** 初始化高德地图服务* @param apiKey - API Key* @returns 服务实例*/
export function initAMapService(apiKey: string): AMapService {if (!amapInstance) {amapInstance = new AMapService({ apiKey });}return amapInstance;
}/*** 获取高德地图服务实例* @returns 服务实例*/
export function getAMapService(): AMapService {if (!amapInstance) {throw new Error('请先调用 initAMapService 初始化');}return amapInstance;
}export default AMapService;

使用说明

  1. 申请 API Key:在高德地图开放平台(https://lbs.amap.com/)注册并申请 Web 服务 API Key。
  2. 安装依赖
    • 确保项目中已安装 axios 和 TypeScript:npm install axios typescript.
    • 在 tsconfig.json 中启用 esModuleInterop 和 strict 选项以确保类型安全。
  3. 初始化服务

    typescript

    import { initAMapService } from './AMapService';const amapService = initAMapService('您的API_KEY');
  4. 功能调用示例
    • 逆地理编码

      typescript

      const addressInfo = await amapService.regeoCode(116.480881, 39.989410, { extensions: 'all' });
      console.log(addressInfo.formattedAddress, addressInfo.addressComponent);
    • 地理编码

      typescript

      const geoInfo = await amapService.geoCode('北京市朝阳区望京街', '北京');
      console.log(geoInfo.longitude, geoInfo.latitude);
    • POI 搜索

      typescript

      const pois = await amapService.searchPOI('咖啡', '北京', { page: 1, offset: 10 });
      console.log(pois);
    • 输入提示

      typescript

      const tips = await amapService.inputTips('故宫', '北京');
      console.log(tips);
    • 批量逆地理编码

      typescript

      const locations = [{ longitude: 116.480881, latitude: 39.989410 },{ longitude: 116.481026, latitude: 39.989614 },
      ];
      const batchResult = await amapService.batchRegeoCode(locations);
      console.log(batchResult);
    • 距离计算

      typescript

      const distanceInfo = await amapService.calculateDistance(116.480881, 39.989410, 116.481026, 39.989614);
      console.log(distanceInfo.distance, distanceInfo.duration);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/96053.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/96053.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

手写 Tomcat

文章目录02 初出茅庐:构造一个极简的 HttpServerRequestResponseHttpServer03 动态 Response : 按照规范构造返回流04 各司其职的 Server : 拆分响应模块与处理模块HttpConnectorHttpProcessor05 Server 性能提升: 设计多个 ProcessorHttpConnectorHttpProcessor06 规范化: 引入…

嵌入式ARM架构学习3——启动代码

一 汇编补充&#xff1a;area reset, code, readonlycode32entry;mov r0, #4 ; r0 4;mov r1, r0 ; r1 r0;mov r2, r1, lsl #1 ;r2 r1 << 1 乘2;mov r3, r1, lsr #1 ;r3 r1 >> 1 除2;mov r4, r1, ror #2;mov r0, #100 ;100是十进制 转为16进制赋值给十进制;mov …

PNPM库离线安装方案

以下是几种可行的方案&#xff0c;推荐优先使用方案一。 方案一&#xff1a;使用离线镜像&#xff08;Offline Mirror&#xff09; - 最优雅、最PNPM的方式 这是 PNPM 官方推荐的处理离线环境的方式。它会在内网电脑上创建一个所有依赖包的压缩文件&#xff08;tarball&#x…

[Wit]CnOCR模型训练全流程简化记录(包括排除BUG)

stepfile:step 00 创建数据集 目录结构 yourproject -data --myset ---images #存放训练图片 ---dev.tsv #测试标签 tsv格式 图片文件名\t内容 ---train.tsv #训练标签 tsv格式 图片文件名\t内容 -train_config.json -train_config_gpu.json -fix_cnocr_encoding.py step 01 创…

Sklearn(机器学习)实战:鸢尾花数据集处理技巧

1.数据集的使用&#xff1a;先使用load导入鸢尾花数据&#xff1a;from sklearn.datasets import load_iris然后定义一个函数来查看鸢尾花数据集&#xff1a;数据集的获取&#xff1a;iris load_iris()print(鸢尾花的数据集&#xff1a;\n,iris)使用iris[DESCR]来查看数据及里…

【企业微信】接口报错:javax.net.ssl.SSLHandshakeException

详细报错信息 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target原因 关于qyapi…

光子芯片驱动的胰腺癌早期检测:基于光学子空间神经网络的高效分割方法

光子芯片驱动的胰腺癌早期检测:基于光学子空间神经网络的高效分割方法 1 论文核心概念 本文提出了一种基于集成光子芯片的光学子空间神经网络(Optical Subspace Neural Network, OSNN),用于胰腺癌的早期检测与图像分割。其核心思想是利用光子芯片的高并行性、低延迟和低能…

Scikit-learn Python机器学习 - 特征降维 压缩数据 - 特征提取 - 主成分分析 (PCA)

锋哥原创的Scikit-learn Python机器学习视频教程&#xff1a; 2026版 Scikit-learn Python机器学习 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili 课程介绍 本课程主要讲解基于Scikit-learn的Python机器学习知识&#xff0c;包括机器学习概述&#xff0c;特征工程(数据…

【Python】pytorch安装(使用conda)

# 创建 PyTorch 虚拟环境 conda create -n pytorch_env python3.10# 激活环境 conda activate pytorch_env# 安装 PyTorch&#xff08;CPU版本&#xff09; conda install pytorch torchvision torchaudio cpuonly -c pytorch# 或者安装 GPU 版本&#xff08;如果有NVIDIA显卡&…

ThreeJS骨骼示例

<html lang"zh-CN"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>骨骼动画混合演示</title><style>body {margin: 0;padding: …

python + Flask模块学习 1 基础用法

目录 Flask 的主要作用 常用扩展 Flask 基本用法 1. 安装 Flask&#xff08;再安装个postman用来调试测试API哈 2. 最小化应用示例 3. 运行应用 Flask 是一个轻量级的 Python Web 框架&#xff0c;它简洁灵活&#xff0c;适合快速开发 Web 应用和 API。它被称为 "微…

python数据可视化之Matplotlib(8)-Matplotlib样式系统深度解析:从入门到企业级应用

作者&#xff1a;浪浪山齐天大圣 描述&#xff1a;深入探索Matplotlib样式系统的核心机制&#xff0c;掌握从基础样式到企业级样式管理的完整解决方案引言 在数据可视化的世界里&#xff0c;一个优秀的图表不仅要准确传达数据信息&#xff0c;更要具备专业的视觉效果。Matplotl…

3.HTTP/HTTPS:报文格式、方法、状态码、缓存、SSLTLS握手

HTTP/HTTPS&#xff1a;报文格式、方法、状态码、缓存、SSL/TLS握手 1. HTTP报文格式 1.1 HTTP请求报文(Request) GET /api/v1/users HTTP/1.1 // 请求行&#xff1a;方法、URI、协议版本 Host: api.example.com // 请求头 (Headers) User-Agent: Mozil…

【慢教程】Ollama4:ollama命令汇总

ℹ️教程说明 Ollama 是一款轻量级本地大模型部署工具&#xff0c;使用广泛&#xff0c;且容易上手&#xff0c;适合作为AI技术的入门。 &#x1f9e9;教程各部分链接&#xff1a; 第一课&#xff1a;ollama运行原理介绍及同类工具对比 ollama运行原理介绍及同类工具对比&am…

JAVA Predicate

简单来说&#xff0c;当我明确知道此次判断的逻辑时就可以直接使用if&#xff0c;但是我这次的判断逻辑可能会随着某个参数变化的时候使用Predicate比如当我想要判断某长段文字中是否包含list<String> 中的元素&#xff0c;并且包含的元素个数大于 list<String>最后…

什么是PFC控制器

一句话概括PFC控制器是一种智能芯片&#xff0c;它通过控制电路中的电流波形&#xff0c;使其与电压波形保持一致&#xff0c;从而减少电力浪费&#xff0c;提高电能的利用效率。PFC控制器IC的核心作用就是控制一颗功率MOSFET的开关&#xff0c;通过特定的电路拓扑&#xff08;…

【P03_AI大模型测试之_定制化 AI 应用程序开发】

git clone https://gitee.com/winner21/aigc-test.git 类似于joycoder的&#xff0c;可以安装在vscode上的通义灵码&#xff1a;https://lingma.aliyun.com/ 1、VSCODE上配置通义灵码 2、创建前后端文件&#xff0c;并引用AI编码代码 3、指定文件&#xff0c;利用AI进行代码优…

人工智能机器学习——决策树、异常检测、主成分分析(PCA)

一、决策树(Decision Tree) 决策树&#xff1a;一种对实例进行分类的树形结构&#xff0c;通过多层判断区分目标所属类别 本质&#xff1a;通过多层判断&#xff0c;从训练数据集中归纳出一组分类规则 优点&#xff1a; 计算量小&#xff0c;运算速度快易于理解&#xff0c;可…

服务器文件同步用哪个工具?介绍一种安全高效的文件同步方案

服务器作为企业核心数据和应用的载体&#xff0c;服务器文件同步已成为IT运维、数据备份、业务协同中不可或缺的一环。然而&#xff0c;面对多样的场景和严苛的需求&#xff0c;选择一个既高效又安全的服务器文件同步工具并非易事。本文将首先探讨服务器文件同步的常见场景、需…

LeetCode 004. 寻找两个正序数组的中位数 - 二分切分与分治详解

一、文章标题 LeetCode 004. 寻找两个正序数组的中位数 - 二分切分与分治详解 二、文章内容 1. 题目概述 题目描述&#xff1a;给定两个已按非降序排列的整数数组 nums1、nums2&#xff0c;设它们长度分别为 m 和 n&#xff0c;要求返回这两个数组合并后有序序列的中位数。…