You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为agm/core中的Marker设置中心锚点以实现绕中心旋转?

解决AGM Core(Angular 4)中Marker自定义图片锚点与旋转问题

嘿,我刚搞定了一模一样的需求!在AGM里用自定义Marker图片时默认锚点在底部,想要让它旋转时绕中心转,得同时搞定锚点设置和旋转逻辑,分享下我的实现步骤:

1. 设置Marker锚点为图片中心

AGM的<agm-marker>组件支持通过iconAnchor属性指定锚点位置,这个值是相对于图片左上角的坐标偏移。假设你的自定义图片尺寸是width x height,那锚点中心的坐标就是[width/2, height/2]。

比如我用的是32x32的图标,模板里这么写:

<agm-marker
  [latitude]="markerLat"
  [longitude]="markerLng"
  [iconUrl]="customMarkerUrl"
  [iconAnchor]="[16, 16]"
></agm-marker>

2. 结合旋转功能实现绕中心转动

参考了@ErDmKo的思路,我们需要通过Google Maps原生的Icon对象来配置旋转属性,同时确保锚点已经设置为中心。在组件类里可以这么处理:

import { Component } from '@angular/core';
import { Icon } from '@agm/core/services/google-maps-types';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html'
})
export class MapComponent {
  markerLat = 39.9042;
  markerLng = 116.4074;
  customMarkerUrl = '/assets/custom-marker.png';
  markerRotation = 45; // 自定义旋转角度

  get markerIcon(): Icon {
    return {
      url: this.customMarkerUrl,
      anchor: new google.maps.Point(16, 16), // 对应图片中心
      rotation: this.markerRotation
    };
  }
}

然后模板里把iconUrl换成icon绑定:

<agm-marker
  [latitude]="markerLat"
  [longitude]="markerLng"
  [icon]="markerIcon"
></agm-marker>

这样设置后,Marker图片就会以中心为锚点,旋转时完全绕中心转动啦!

特别感谢@ErDmKo提供的旋转思路,帮了大忙!

内容的提问来源于stack exchange,提问作者Srikanth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:35:38