百度地图开发探索 angular7 (typescript) 添加参考点、定位点与自定义弹窗

添加参考点并获取位置

话不多说,看图说话
在这里插入图片描述
分析一下此点和弹窗的组成:
1、上图的蓝色图标为一个marker
2、生成一个marker需要point,生成point需要两个坐标(经纬度)
3、上方的弹窗是依赖于marker生成的(弹窗自定义样式下面会有整理)

// 参考点
  referencePoint(e: any) {
    const point = new BMap.Point(e.point.lng, e.point.lat); // 创建point
    const poiIcon = new BMap.Icon(
      '../../../../../assets/font/poi_marker.png',
      new BMap.Size(50, 50)
    ); // 增加图标图
    const marker = new BMap.Marker(point, {
      width: '40px',
      height: '40px',
      offset: new BMap.Size(0, 0),
      icon: poiIcon,
    }); // 创建marker
    this.refPoint.push(point); // 记录的方法,忽略
    this.refMarker.push(marker); // 记录的方法,忽略
    this.map.addOverlay(marker); // 将标注添加到地图中
    // 绑定图标的点击事件,当点击时弹出弹窗
    marker.addEventListener('click', (ev: any) => {
      this.refMarker.forEach((el: any, index: number) => {
        if (el === marker) {
          this.refPointPop(index);  // 弹窗事件(在下方)
        }
      });
    }); 
    this.refMarker.forEach((el: any, index: number) => {
      if (el === marker) {
        this.refPointPop(index); // 弹窗事件(在下方)
      }
    });
  }

注意:Size属性要慎用,参考点的Size(50,50) 平移了很小范围还好,如果大了的话 在地图上会有阴影遮盖,会导致点不到地图。

弹窗:

// 添加参考点的弹窗
  refPointPop(clickIndex: number) {
    // 创建地址解析器实例
    const myGeo = new BMap.Geocoder();
    myGeo.getLocation(this.refPoint[clickIndex], (rs: any) => {
      const address_ref =
        rs.addressComponents.province +
        ' ' +
        rs.addressComponents.city +
        ' ' +
        rs.addressComponents.district +
        ' ' +
        rs.addressComponents.street;
      const content = `<div class="title_ref">
      <span>参考点</span></div>
  <div class="address_ref">${address_ref}</div>
  <button id="del_button_ref" class="button">删除该点</button>`;
  	  // 让弹窗单例展示
      if (this.refInfoWindow) {
        this.refMarker.forEach((ele: any) => {
          this.refInfoWindow.close(ele);
        });
      }
      this.refInfoWindow = new BMapLib.InfoBox(this.map, content, {
        boxStyle: {
          background: '#fff',
          borderRadius: '5px',
          width: '250px',
          height: '150px',
        },
        closeIconUrl: '../../../../../assets/font/close.png',
        closeIconMargin: '10px 10px 0 0',
        align: INFOBOX_AT_TOP,
        offset: new BMap.Size(0, 20),
      }); // 创建信息窗口对象
      this.refInfoWindow.open(this.refMarker[clickIndex]);

      setTimeout(() => {
        const delBtn = document.getElementById('del_button_ref');
        // 删除参考点按钮监听
        delBtn.addEventListener('click', (event: any) => {
          this.map.removeOverlay(this.refMarker[clickIndex]); // 移除点
          this.refMarker.splice(clickIndex, 1);
          this.refPoint.splice(clickIndex, 1);
          this.refInfoWindow.close();
        });
      });
    });
  }

Geocoder:用于获取用户的地址解析。也就是我们框框中的地址
myGeo.getLocation的回调中有点击点的坐标,但不是精确坐标,如果需要精确坐标需要后台解析,或前端另外解析。
content :里面放着弹窗的内容,弹窗的样式如果在自己的.scss文件中无法修改,到总得css文件中修改样式
BMapLib.InfoBox:使用infoBox生成的弹窗是可以自定义样式的。 是需要引入的

<script src="http://api.map.baidu.com/library/InfoBox/1.2/src/InfoBox.js"></script>

InfoBox的使用详解请点击
offset:偏移值,不建议修改过多,会有阴影影响点击
弹窗中的事件需要用原生js来写获取,弹窗加载到页面上会有延迟,所以使用了个setTimeout来处理,可能会有更好的方式。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 安装必要的依赖 使用 Angular 框架实现高德地图需要安装 @types/amap-js-api 和 @types/amap-js-sdk 两个依赖。 ```bash npm install @types/amap-js-api @types/amap-js-sdk --save-dev ``` 2. 配置 highCharts API Key 在 app.module.ts 中配置高德地图的 API Key: ```typescript import { AMapLoaderService, LoaderOptions } from '@delon/theme'; // ... const options: LoaderOptions = { key: '你的高德地图 API Key', }; // ... @NgModule({ imports: [ // ... ], declarations: [ // ... ], providers: [ // ... AMapLoaderService, { provide: 'DA_STORE_TOKEN', useValue: {}, }, { provide: 'HIGHCHARTS_MODULES', useFactory: () => [more, exporting], }, { provide: HIGHCHARTS_MODULES, useFactory: () => [highcharts], } ], }) export class AppModule {} ``` 3. 创建地图的 wrapper 服务类 我们需要创建一个 wrapper 类,封装高德地图的调用,以便在内部进行维护和扩展。 ```typescript import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MapService { private AMap: any; constructor() { this.loadMapScript(); } private loadMapScript() { const script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${environment.amapApiKey}&callback=initAMap`; script.onerror = () => { console.error('Could not load map script!'); }; document.body.appendChild(script); } public getMapInstance() { return new Promise<any>((resolve, reject) => { if (this.AMap) { resolve(this.AMap); } else { const callbackName = `initAMap${Math.floor(Math.random() * 10000)}`; window[callbackName] = () => { this.AMap = window.AMap; resolve(this.AMap); delete window[callbackName]; }; const script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${environment.amapApiKey}&callback=${callbackName}`; script.onerror = () => { console.error('Could not load map script!'); delete window[callbackName]; reject(); }; document.body.appendChild(script); } }); } } ``` 在上面的代码中,我们加载了高德地图 SDK 并在异步加载结束后返回 AMap 实例。 4. 在组件中使用地图查询服务 现在我们可以在组件中使用地图查询服务了。让我们创建一个 search.component.ts 文件实现这个服务。 ```typescript import { Component, OnInit } from '@angular/core'; import { MapService } from '../services/map.service'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.scss'] }) export class SearchComponent implements OnInit { constructor(private mapService: MapService) {} ngOnInit() {} searchPlace(query: string) { this.mapService.getMapInstance().then(AMap => { const placeSearch = new AMap.PlaceSearch({ pageSize: 10, pageIndex: 1, city: '全国', map: new AMap.Map('map', { zoom: 15, resizeEnable: true, }), panel: 'panel' }); placeSearch.search(query, function (status: any, result: any) { // 处理查找结果 }); }); } } ``` 这里我们定义了一个 `searchPlace` 方法,用来查询地点。当我们调用 `searchPlace(query)` 的时候,它将使用 `MapService` 实例来获取 AMap 实例,然后使用 AMap 的 `PlaceSearch` 类查询地点。 5. 在 HTML 模板中添加搜索输入框和地图 最后,我们将在 HTML 模板中创建搜索输入框和地图。 ```html <div class="search-container"> <input type="text" [(ngModel)]="searchQuery" placeholder="请输入地点名称"> <button (click)="searchPlace(searchQuery)">搜索</button> </div> <div id="map" style="height: 400px;"></div> <div id="panel"></div> ``` 现在我们已经实现了一个简单的搜索地点页面,它可以通过高德地图查询地点并在地图上展示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值