项目里是使用的ngx-amap
在html引入地图
<ngx-amap [resizeEnable]="true" [center]="[116.397428, 39.90923]" [zoom]="13" class="map-container" (naReady)="onMapReady($event)">
<!-- 出现放大工具 -->
<amap-tool-bar></amap-tool-bar>
</ngx-amap>
在css设置地图宽高
.map-container{
width: 100%;
height: 800px;
border-radius:8px;
}
组件核心ts代码
import { AmapPluginLoaderService } from 'ngx-amap';
constructor(private plugin: AmapPluginLoaderService) {
}
onMapReady(map: AMap.Map) {
this.plugin.load('AMap.Scale').subscribe(() => {
map.addControl(new AMap['Scale']({ position: 'RT' }));
})
}
在module里引入地图,key是使用高德地图需要的,需要申请
import { NgxAmapModule } from 'ngx-amap';
@NgModule({
imports: [
NgxAmapModule.forRoot({ apiKey: key})
]
})
export class TrajectoryPositionModule { }
项目的package.json配置,angular的环境是版本12
"dependencies": {
"@angular/animations": "~12.2.0",
"@angular/cdk": "^12.2.13",
"@angular/common": "~12.2.0",
"@angular/compiler": "~12.2.0",
"@angular/core": "~12.2.0",
"@angular/forms": "~12.2.0",
"@angular/platform-browser": "~12.2.0",
"@angular/platform-browser-dynamic": "~12.2.0",
"@angular/router": "~12.2.0",
"@types/amap-js-api-scale": "^1.4.2",
"amap-js-api-typings": "^1.0.1",
"ngx-amap": "^3.0.5"
},
"devDependencies":{
"@types/amap-js-api": "^1.4.10",
"@types/amap-js-api-autocomplete": "^1.4.1",
"@types/amap-js-api-driving": "^1.4.1",
"@types/amap-js-api-heatmap": "^1.4.2",
"@types/amap-js-api-place-search": "^1.4.1",
"@types/amap-js-api-tool-bar": "^1.4.1",
"@types/amap-js-api-transfer": "^1.4.1",
}
遇到的问题总结:
1.Property ‘Scale’ does not exist on type ‘typeof AMap’.
可能使用new AMap.Scale时ts的类型问题,Scale找不到但我按住ctrl点进去发现本地有Scale,后来通过换一种方式
new AMap['Scale']
实现了运行不报错
2 比例尺在最左下出现一点点
我发现放大时左下角总有个东西在动,后来我把比例尺位置调了一下,出来了,临时解决方案放在右上角
map.addControl(new AMap['Scale']({ position: 'RT' }))
,后来发现原来是因为地图父容器设置的高度影响了
position取值: LT:左上角; RT:右上角; LB:左下角; RB:右下角; 默认位置:LB,如果还想偏移,则需要通过offset属性来设置,如
map.addControl(new AMap['Scale']({ position: 'LT',offset: new AMap.Pixel(80, 10) }));
参考资料:
1.ngx-amap演示
2.ngx-amap api文档
3.高德地图文档
4.博客 | 高德地图控件 angular应用
记录一下探索在angular用高德地图比例尺的过程,如果你能看到该文,希望能给你带来灵感与启发。