【问题标题】:Is there a way to set the bounds and Zoom level in AGM Map?有没有办法在 AGM 地图中设置边界和缩放级别?
【发布时间】:2018-07-29 15:42:22
【问题描述】:

我在我的 angular 4 应用程序中使用AGM maps,我遇到了一些问题,我将从 api 获取的多个标记作为纬度和经度数组。我想设置完全覆盖地图上所有标记的缩放级别。即使一个国家的一个标记和另一个国家的另一个标记,它也应该在加载时设置缩放级别以显示地图上的所有标记。 有没有办法在 AGM 角度图中做到这一点?谁能帮帮我

【问题讨论】:

    标签: angular google-maps google-maps-api-3 google-maps-markers angular-google-maps


    【解决方案1】:
        <agm-map #agmap   
          [zoom]="zoom"
          [disableDefaultUI]="false"
          [zoomControl]="false"
          [fitBounds]="true">
            <agm-marker [agmFitBounds]="true" [latitude]="curretAddLat" [longitude]="curretAddLng"></agm-marker>
          </agm-map>
    ***Above code will help you with AGM MAP.
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    如果您出于某种原因不使用 agm-marker(您使用 html 标记,就像我一样)那么您的组件可能不支持 agmFitBounds 访问器。为了使它正常工作,编写实现 FitBoundsAccessor 的自定义组件:

    import { ChangeDetectionStrategy, Component, forwardRef, Input, OnChanges, SimpleChanges } from '@angular/core';
    import { FitBoundsAccessor, FitBoundsDetails } from '@agm/core';
    import { BehaviorSubject, Observable } from 'rxjs';
    
    @Component({
        selector: 'guide-map-bounds',
        template: `<ng-content></ng-content>`,
        providers: [{ provide: FitBoundsAccessor, useExisting: forwardRef(() => MapBoundsComponent) }],
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class MapBoundsComponent implements FitBoundsAccessor, OnChanges {
        @Input() latitude: number;
        @Input() longitude: number;
    
        private fitBoundsDetails$ = new BehaviorSubject<FitBoundsDetails>(null);
    
        constructor() { }
    
        ngOnChanges(changes: SimpleChanges): void {
            const latLng: google.maps.LatLngLiteral = { lat: this.latitude, lng: this.longitude };
    
            this.fitBoundsDetails$.next({ latLng });
        }
    
        getFitBoundsDetails$(): Observable<FitBoundsDetails> {
            return this.fitBoundsDetails$.asObservable();
        }
    }
    

    然后在你的 html 里面,agm-map

    <guide-map-bounds [agmFitBounds]="true" *ngFor="let marker of markers" [latitude]="marker.lat" [longitude]="marker.lon">
      <agm-html-overlay [latitude]="marker.lat" [longitude]="marker.lon">
        <div class="marker" >
          
        </div>
      </agm-html-overlay>
    </guide-map-bounds>
    

    请注意 agm-html-overlay 是不支持 agmFitBounds 的自定义组件

    【讨论】:

      【解决方案3】:

      自 2018 年 9 月以来,有 AgmFitBounds 指令。超级简单。

      <agm-map
        style="width:100vw; height:100vh;"
        [fitBounds]="true">
      
        <agm-marker
          *ngFor="let location of locations"
          [latitude]="location.latitude"
          [longitude]="location.longitude"
          [agmFitBounds]="true"></agm-marker>
      </agm-map>
      

      【讨论】:

      • 为此,您需要将 rxjs 升级到版本 6: npm install rxjs@6 rxjs-compat@6 --save
      • 对我不起作用。如果我输入此代码,则地图始终保持放大状态。它不会根据数据进行更改。有什么可以帮助我的吗?
      • @KrushnaJoshi 最好你提出一个新问题并向我们展示你目前拥有的代码。
      • @PapaMufflon 没问题想出了一个办法。当数据发生变化时,我通过重新初始化地图来解决这个问题。
      • 多边形是否存在类似的东西? stackblitz.com/edit/…
      【解决方案4】:

      @renil-babu

      您不必在mapReady 上执行fitBounds,而是必须在添加标记订阅块中执行此操作

            const bounds: LatLngBounds = new google.maps.LatLngBounds();
            for (const mm of this.markers) {
              bounds.extend(new google.maps.LatLng(mm.lat, mm.lng));
            }
            // @ts-ignore
            this.agmMap._mapsWrapper.fitBounds(bounds);
      

      【讨论】:

      • @Papa Mufflon 嗨,它给了我一些错误 No provider for FitBoundsAccessor ("S" style="position: relative; overflow: hidden;">
      【解决方案5】:

      目标

      我们想设置 AGM 地图的缩放级别以显示地图上的所有标记。通常在 Google Maps JavaScript API 中,您使用 google.maps.Map 类的 fitBounds() 方法来实现此目的。

      https://developers.google.com/maps/documentation/javascript/reference/3/map

      因此,我们必须获取地图对象的实例(JavaScript API 实例)并在其上应用fitBounds()

      解决方案

      我创建了一个简单的示例,它有一个模拟服务,它为 5 个标记提供 JSON 数据,并使用 AGM 地图绘制地图和标记。在这个例子中,我使用 @ViewChild 装饰器来获取 AGM 地图的实例并监听 mapReady 事件以获取地图对象的实例(来自 JavaScript API)。获得地图实例后,我可以轻松创建 LatLngBounds 对象并在地图对象上调用 fitBounds()。看看 app.component.ts 中的ngAfterViewInit() 方法,了解一下。

      代码 sn-p

      app.component.ts

      import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
      import { MyMarker } from './marker';
      import { MarkersService } from './markers.service';
      import { GoogleMapsAPIWrapper, AgmMap, LatLngBounds, LatLngBoundsLiteral} from '@agm/core';
      
      declare var google: any;
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent implements OnInit, AfterViewInit {
      
        title = 'AGM project (so48865595)';
        lat = 41.399115;
        lng = 2.160962;
        markers: MyMarker[];
      
        @ViewChild('AgmMap') agmMap: AgmMap;
      
        constructor(private markersService: MarkersService) { }
      
        ngOnInit() {
          this.getMarkers();
        }
      
        ngAfterViewInit() {
          console.log(this.agmMap);
          this.agmMap.mapReady.subscribe(map => {
            const bounds: LatLngBounds = new google.maps.LatLngBounds();
            for (const mm of this.markers) {
              bounds.extend(new google.maps.LatLng(mm.lat, mm.lng));
            }
            map.fitBounds(bounds);
          });
        }
      
        getMarkers(): void {
          this.markers = this.markersService.getMarkers();
        }
      
        mapIdle() {
          console.log('idle');
        }
      }
      

      app.component.html

      <h1>{{ title }}</h1>
      
      <!-- this creates a google map on the page with the given lat/lng from -->
      <!-- the component as the initial center of the map: -->
      <agm-map #AgmMap [latitude]="lat" [longitude]="lng" (idle)="mapIdle()">
        <agm-marker *ngFor="let p of markers" [latitude]="p.lat" [longitude]="p.lng"></agm-marker>
      </agm-map>
      

      结论

      如果您想查看完整示例,请下载示例项目:

      https://github.com/xomena-so/so48865595

      我希望这会有所帮助!

      【讨论】:

      • 嗨..我正在从服务器加载数据,所以需要一些时间。我只想在收到来自服务器的数据时设置边界。你能帮忙吗
      • 您从 @agm/core 导入了 LatLngBounds,但类型不完全匹配。使用来自 @types/googlemaps 的类型修复了我的错误:const bounds: google.maps.LatLngBounds = new google.maps.LatLngBounds();
      • LatLngBoundsCannot invoke an expression whose type lacks a call signature 打字稿错误的另一个更简单的解决方案是将// @ts-ignore 添加到map.fitBounds(bounds) 上方的行中。另外,我希望我能两次投票赞成这个答案! XD
      • 另外,您需要将(mapReady)="onMapReady($event)" 添加到您的&lt;agm-map&gt; html 中,然后将fitBounds 的内容放入您的onMapReady(map: AgmMap) 函数中,因为agmMap.mapReady.subscribe 不再起作用了
      • 我使用了这个实现,在某些情况下,this.agmMap 是未定义的。知道它是怎么发生的吗?
      【解决方案6】:

      我让它与LatLngBounds() 函数一起工作。这是sn-p。

      import {AgmInfoWindow, MapsAPILoader} from '@agm/core';
      
      latlngBounds: any;
      
      // fits the map to the bounds
          if (this.points.length.) {
            this.mapsAPILoader.load().then(() => {
                this.latlngBounds = new window['google'].maps.LatLngBounds();
                _.each(this.points, location => {
                  this.latlngBounds.extend(new window['google'].maps.LatLng(location.lat, location.lng));
                });
              }
            );
          }
      

      【讨论】:

        猜你喜欢
        • 2013-02-27
        • 2019-05-25
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-10
        相关资源
        最近更新 更多