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
英文地址,請注明出處:http://en.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;要求返回這兩個數組合并后有序序列的中位數。…