Angular封装高德地图组件实现输入框搜索,地图点击选地点

本文主要是介绍Angular封装高德地图组件实现输入框搜索,地图点击选地点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Angular封装高德地图组件实现输入框搜索,地图点击选地点(Angular17版本)

话不多说直接上代码

创建一个独立组件
在这里插入图片描述
html代码:

<div style="position: relative;"><input #searchInput nz-input placeholder="请输入地址"/><div #mapContainer style="width: 100%;height: 350px;"></div>
</div>

样式less

@import "src/styles/themes/mixin";.themeMixin({:host {position: relative;.toolbar {z-index: 9999;top: 8px;right: 8px;width: 200px;}}
});

ts代码:

import {AfterViewInit,Component,ElementRef,EventEmitter,Input,OnInit,Output, SimpleChanges,ViewChild
} from '@angular/core';
import {Observable, Observer, Subject} from "rxjs";
import {getPointsCenter} from "../../../util/gis";
import {NzInputDirective} from "ng-zorro-antd/input";
@Component({selector: 'app-site-pick',standalone: true,imports: [NzInputDirective],templateUrl: './site-pick.component.html',styleUrl: './site-pick.component.less'
})
export class SitePickComponent implements OnInit, AfterViewInit{@ViewChild('mapContainer', {static: false}) mapContainer: ElementRef@ViewChild('searchInput', {static: false}) searchInput: ElementRef@Output("inputChange") inputChange = new EventEmitter<{ lonlat: any, siteName: any, adCode: any }>();@Input() lonlat: string;@Input() locationName: string;@Input("boundary") boundary: stringmap: any;overlays: any[] = [];searchAdCode = '010'defaultCenter = [116.397755, 39.903179]currentMarker: any; // 用于存储当前标记的引用drawMapEvent = new Subject()mapLoaded = false; // 标志位,判断地图是否已加载private mapLoadSubject = new Subject<void>(); // 用于触发地图加载完成事件ngOnInit(): void {this.drawMapEvent.subscribe(next => {this.currentPosition().subscribe(center => {this.addSearchPlugin();});});}addSearchPlugin(): void {const placeSearch = new window['AMap'].PlaceSearch({map: this.map,city: this.searchAdCode});const auto = new window['AMap'].Autocomplete({input: this.searchInput.nativeElement,city: this.searchAdCode});window['AMap'].Event.addListener(auto, "select", (e) => {placeSearch.search(e.poi.name, (status, result) => {if (status === 'complete' && result.info === 'OK' && result.poiList.pois.length > 0) {const poi = result.poiList.pois[0];placeSearch.getDetails(poi.id, (detailStatus, detailResult) => {if (detailStatus === 'complete' && detailResult.poiList.pois.length > 0) {const detailedPoi = detailResult.poiList.pois[0];const adCode = [detailedPoi.pname,detailedPoi.cityname,detailedPoi.adname].filter(ac => ac);if (adCode.length === 2) {adCode.splice(1, 0, adCode[0]);}const adCodeStr = adCode.join(',');const location = detailedPoi.location;const siteName = detailedPoi.name;const lonlat = location.lng + ',' + location.lat;this.inputChange.emit({ lonlat: lonlat, siteName: siteName, adCode: adCodeStr });}});}});});}currentPosition(): Observable<any> {return new Observable<any>((observer: Observer<any>) => {new window['AMap'].Geolocation({enableHighAccuracy: false,timeout: 5000,offset: [10, 20],zoomToAccuracy: true,position: 'RB'}).getCityInfo((status, result) => {if (status == 'complete') {if (this.boundary && typeof this.boundary === 'string') {try {const center = getPointsCenter(this.boundary.split(';'));observer.next(center);} catch (e) {observer.next(this.defaultCenter);}} else {observer.next(result.position);this.searchAdCode = result.adcode;this.addSearchPlugin();}} else {console.error(result, 'Geolocation');observer.next(this.defaultCenter);}});});}ngAfterViewInit(): void {setTimeout(() => {this.map = new window['AMap'].Map(this.mapContainer.nativeElement, {resizeEnable: true,zoom: 14});this.map.on('click', (e) => {const lonlat = e.lnglat.getLng() + ',' + e.lnglat.getLat();this.resolveLocation(lonlat);});this.map.on('complete', () => {this.mapLoaded = true; // 地图加载完成this.mapLoadSubject.next(); // 触发地图加载完成事件this.initMarker();});this.drawMapEvent.next(null);}, 0);}initMarker(): void {if (!this.map) {console.error('地图尚未加载完成');return;}if (this.currentMarker) {this.map.remove(this.currentMarker);}if (this.lonlat) {const [lon, lat] = this.lonlat.split(',').map(Number);const position = new window['AMap'].LngLat(lon, lat);this.currentMarker = new window['AMap'].Marker({map: this.map,position: position});}}resolveLocation(lonlat: string): void {const [lng, lat] = lonlat.split(',').map(Number);const position = new window['AMap'].LngLat(lng, lat);const geocoder = new window['AMap'].Geocoder();geocoder.getAddress(position, (status, result) => {if (status === 'complete' && result.regeocode) {const address = result.regeocode.formattedAddress;const addressComponent = result.regeocode.addressComponent;const adCode = [addressComponent.province, addressComponent.city, addressComponent.district].map(ac => ac && typeof ac === 'object' ? ac.adcode : ac).filter(ac => ac);if (adCode.length === 2) {adCode.splice(1, 0, adCode[0]);}const adCodeStr = adCode.join(',');this.searchInput.nativeElement.value = address;this.inputChange.emit({ lonlat: lonlat, siteName: address, adCode: adCodeStr });} else {console.error('根据经纬度获取地址失败:', result);}});this.initMarker();}updateMapLocation(): Promise<void> {return new Promise((resolve, reject) => {if (!this.map) {console.error('地图尚未加载完成');return reject('地图尚未加载完成');}const [lon, lat] = this.lonlat.split(',').map(Number);const position = new window['AMap'].LngLat(lon, lat);if (this.currentMarker) {this.currentMarker.setPosition(position);} else {this.currentMarker = new window['AMap'].Marker({map: this.map,position: position});}this.map.setCenter([lon, lat]);resolve();});}getAddressFromLonLat(): void {const [lng, lat] = this.lonlat.split(',').map(Number);const geocoder = new window['AMap'].Geocoder();const position = new window['AMap'].LngLat(lng, lat);geocoder.getAddress(position, (status, result) => {if (status === 'complete' && result.regeocode) {const address = result.regeocode.formattedAddress;const addressComponent = result.regeocode.addressComponent;const adCode = [addressComponent.province, addressComponent.city, addressComponent.district].map(ac => ac && typeof ac === 'object' ? ac.adcode : ac).filter(ac => ac);if (adCode.length === 2) {adCode.splice(1, 0, adCode[0]);}const adCodeStr = adCode.join(',');this.searchInput.nativeElement.value = address;this.inputChange.emit({ lonlat: this.lonlat, siteName: address, adCode: adCodeStr });} else {console.error('根据经纬度获取地址失败:', result);}});}ngOnChanges(changes: SimpleChanges): void {if (changes['lonlat'] && this.lonlat) {if (this.mapLoaded) {this.updateMapLocation().then(() => {this.getAddressFromLonLat(); //根据 lonlat 获取地名});} else {this.mapLoadSubject.subscribe(() => { // 订阅地图加载完成事件this.updateMapLocation().then(() => {this.getAddressFromLonLat(); //根据 lonlat 获取地名});});}}}
}

如果 this.drawMapEvent.next(null); 报错改成 this.drawMapEvent.next();即可 因为我引入的 rxjs@7.5.7,

我这里对数据进行了处理:传出外部的数据类型:{ lonlat: any, siteName: any, adCode: any }

lonlat是经纬度,用",“逗号分隔
siteName是地点名
adCode是行政区code 用”,"分隔

使用

由于我做了表单的传值 可以直接在Form表单使用

      <nz-form-item><nz-form-label [nzSpan]="4" nzFor="lonlat">场地地址</nz-form-label><nz-form-control [nzSpan]="16" nzHasFeedback nzErrorTip="lonlat"><app-site-pick[lonlat]="form.get('lonlat').value"(inputChange)="inputChange($event)"></app-site-pick></nz-form-control></nz-form-item>
  /*** 地图input框选中返回lonlat+name* @param $event*/inputChange($event: any) {this.form.get('lonlat').setValue($event.lonlat);this.form.get('address').setValue($event.siteName)}

这里我只需要传入lonlat即可回显地点
inputChange()方法可以监听改变的数据,然后数据格式就自己处理吧
当然也可以通过[(ngModel)]进行绑定

还有最关键的高德地图的key,securityJsCode(自己去官网上注册)

在全局上配置写上:app.config.ts

export const appConfig: ApplicationConfig = {providers: [importProvidersFrom(HttpClientModule, NzMessageModule, NzDrawerModule, NzModalModule, NzNotificationModule,NzSwitchModule),provideAnimations(),provideRouter(appRoutes,withPreloading(PreloadSelective),withComponentInputBinding() // 开启路由参数绑定到组件的输入属性,ng16新增特性),// 初始化配置{provide: APP_INITIALIZER,useFactory: (bootstrap: BootstrapService) => () => {return bootstrap.init();},deps: [BootstrapService],multi: true,},// 国际化{provide: NZ_I18N,useFactory: (localId: string) => {switch (localId) {case 'en':return en_US;default:return zh_CN;}},deps: [LOCALE_ID]},{provide: HTTP_INTERCEPTORS, useClass: GlobalInterceptor, multi: true},{provide: AMAP_CONFIG, useValue: {securityJsCode: '9a2396b90169c48885aXXXXX6',key: 'de07643eaabaXXXXXX29284'}}]
};
{provide: AMAP_CONFIG, useValue: {securityJsCode: '9a2396b9XXX2c0c3eaf6fdb6',key: 'de07643XXXX5a5629284'}
}

这个就是

然后在你的BootstrapService 中添加启动 loadAMap

import {Inject, Injectable} from '@angular/core';
import {registerLocaleData} from "@angular/common";
import zh from "@angular/common/locales/zh";
import {NzIconService} from "ng-zorro-antd/icon";
import {load} from "@amap/amap-jsapi-loader";
import {AMAP_CONFIG, AMAPConfig} from "../config";
import {SkinService} from "./skin.service";@Injectable({providedIn: 'root'})
export class BootstrapService {constructor(private nzIconService: NzIconService,private skinService: SkinService,@Inject(AMAP_CONFIG) private amapConfig: AMAPConfig) {}init(): void {// 注册本地化语言包registerLocaleData(zh);// 注册icon// this.nzIconService.addIconLiteral('outline:clear', '')// 初始化设置主题this.skinService.loadTheme(this.skinService.localTheme()).then();// 加载地图this.loadAMap()}loadAMap(): void {window['_AMapSecurityConfig'] = {securityJsCode: this.amapConfig.securityJsCode, // 安全密钥};load({"key": this.amapConfig.key,"version": "2.0",   // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15"plugins": ['AMap.Geolocation','AMap.PolygonEditor','AMap.PlaceSearch','AMap.AutoComplete','AMap.Polyline','AMap.Geocoder'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等"AMapUI": {// 是否加载 AMapUI,缺省不加载"version": '1.1',// AMapUI 缺省 1.1"plugins": ['overlay/SimpleMarker'],},"Loca": { // 是否加载 Loca, 缺省不加载"version": '2.0'  // Loca 版本,缺省 1.3.2},}).then((AMap) => {window['AMap'] = AMap}).catch(e => {console.log(e);})}
}

成品展示:

在这里插入图片描述

在这里插入图片描述

这篇关于Angular封装高德地图组件实现输入框搜索,地图点击选地点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1053900

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

无人叉车3d激光slam多房间建图定位异常处理方案-墙体画线地图切分方案

墙体画线地图切分方案 针对问题:墙体两侧特征混淆误匹配,导致建图和定位偏差,表现为过门跳变、外月台走歪等 ·解决思路:预期的根治方案IGICP需要较长时间完成上线,先使用切分地图的工程化方案,即墙体两侧切分为不同地图,在某一侧只使用该侧地图进行定位 方案思路 切分原理:切分地图基于关键帧位置,而非点云。 理论基础:光照是直线的,一帧点云必定只能照射到墙的一侧,无法同时照到两侧实践考虑:关

【 html+css 绚丽Loading 】000046 三才归元阵

前言:哈喽,大家好,今天给大家分享html+css 绚丽Loading!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、信息💡1.简介:💡2.外观描述:💡3.使用方式:💡4.战斗方式:💡5.提升:💡6.传说: 📚三、源代码,上代码,可以直接复制使用🎥效果🗂️目录✍️

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

认识、理解、分类——acm之搜索

普通搜索方法有两种:1、广度优先搜索;2、深度优先搜索; 更多搜索方法: 3、双向广度优先搜索; 4、启发式搜索(包括A*算法等); 搜索通常会用到的知识点:状态压缩(位压缩,利用hash思想压缩)。

hdu1240、hdu1253(三维搜索题)

1、从后往前输入,(x,y,z); 2、从下往上输入,(y , z, x); 3、从左往右输入,(z,x,y); hdu1240代码如下: #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#inc

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象