【问题标题】:Subscribing to data within JS Google Maps订阅 JS 谷歌地图中的数据
【发布时间】:2020-04-20 07:46:21
【问题描述】:

我正在尝试在动态脚本中更改地图的中心。问题是我确实得到了我订阅的数据,但它不会改变地图的中心。我通过在组件内创建一个 setInterval() 并在我在组件外执行该方法后查看数据是否更改来对此进行了测试。下面是代码示例

https://codesandbox.io/s/joey-basic-gmaps-lw5d4

export class AppComponent implements OnInit, OnChanges {
  public markerLat = 39;
  public markerLng = -76;
  title = "CodeSandbox";
  private apiKey = environment.googleMapsAPIkey;

  constructor(private data: DataService) {
    const dynamicScripts = [
      "https://maps.googleapis.com/maps/api/js?key=" + this.apiKey
    ];
    for (var i = 0; i < dynamicScripts.length; i++) {
      const node = document.createElement("script");
      node.src = dynamicScripts[i];
      node.type = "text/javascript";
      node.async = true;
      node.charset = "utf-8";
      document.getElementsByTagName("head")[0].appendChild(node);
    }
  }
  ngOnInit() {
    this.data.markerLat.subscribe(markerLat => this.markerLat = markerLat);
    this.data.markerLng.subscribe(markerLng => this.markerLng = markerLng);
    setTimeout(() => {
      this.initMap();
    }, 1000);
  }
  ngOnChanges() {
    setTimeout(() => {
      this.initMap();
    }, 1000);
  }
  ngOnDestroy() {
    this.data.markerLat.subscribe(markerLat => this.markerLat = markerLat).unsubscribe();
    this.data.markerLng.subscribe(markerLng => this.markerLng = markerLng).unsubscribe();
  }
  initMap() {
    const google = window.google;

    const center = { lat: this.markerLat, lng: this.markerLng };
    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 8,
      center: center
    });
    const marker = new google.maps.Marker({ position: center, map: map });
  }
}

【问题讨论】:

  • @Chellappanவ 市场是可见的......它只是不会改变位置
  • 将 initMap 方法移到 subscribe 方法中
  • @Chellappanவ 我不知道你的意思……你能告诉我吗

标签: javascript angular google-maps observable


【解决方案1】:

由于您是从异步源获取数据,因此 initMap 的执行顺序会有所不同。将您的 initMap 方法移动到 subscribe 块中。使用 forkJoin 获取 lat 和 lng 可观察到的首先完成。

试试这个

    import { forkJoin } from 'rxjs';

    export class AppComponent implements OnInit, OnChanges {

    ngOnInit() {
       const latLng = forkJoin(
       this.data.markerLat,
       this.data.markerLng
       ).subscribe(([markerLat, markerLng])=>{
        this.markerLat = markerLat;
        this.markerLng = markerLng;
        this.initMap();
     })
   }
 }

【讨论】:

  • 我知道你在做什么,这是有道理的......但是地图无法加载,我没有从控制台收到错误
  • 您能否在订阅方法中进行控制台并查看您是否获取数据?
  • 它没有安慰任何东西......我认为它根本没有达到方法
  • 你必须完成 observable 才能获得价值:codesandbox.io/s/…
  • 地图初始化后不能用setcenter方法改变坐标的中心吗
猜你喜欢
  • 1970-01-01
  • 2018-10-26
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多