在 ngOnInit 事件上分配经度和纬度值时,城市不显示在地图上?

city not display on map when assign values of longitude and latitude on ngOnInit Event?

问题

当在 ngOnInt 事件地图上分配经纬度值时,城市或区域显示为空?

我在 angular 7 .

上工作

在 ngOnInit 事件地图城市或区域上分配经纬度值时显示为空

根据经纬度城市必须显示为纽约但显示为空。

如何解决问题?

我在下面尝试的是:

import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'angular-gmap';
  @ViewChild('mapContainer', { static: false }) gmap: ElementRef;
  map: google.maps.Map;
 lat = 0;
 lng = 0;

  coordinates = new google.maps.LatLng(this.lat, this.lng);

  mapOptions: google.maps.MapOptions = {
    center: this.coordinates,
    zoom: 8
  };

  marker = new google.maps.Marker({
    position: this.coordinates,
    map: this.map,
    title: 'Hello World!'
  });
  ngOnInit() {
   this. lat = 40.73061;
    this.lng = -73.935242;

  }
  ngAfterViewInit() {
    this.mapInitializer();
  }

  mapInitializer() {
    this.map = new google.maps.Map(this.gmap.nativeElement, this.mapOptions);
    this.marker.setMap(this.map);
  }
}

地图不显示城市的图像显示

您在 ngOnInit 中创建 coordinatesmapOptions before 设置 latlng。所以坐标有lat和lng的初始值:0和0.

您的代码可以简化为

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'angular-gmap';
  @ViewChild('mapContainer', { static: false }) gmap: ElementRef;

  // no need for instance fields that no one uses

  // no need for ngOnInit

  ngAfterViewInit() {
    this.mapInitializer();
  }

  mapInitializer() {
    // the coordinates are created with the correct lat and lng. Not with 0, 0
    const coordinates = new google.maps.LatLng(40.73061, -73.935242);

    const mapOptions: google.maps.MapOptions = {
      center: coordinates,
      zoom: 8
    };

    const marker = new google.maps.Marker({
      position: coordinates,
      title: 'Hello World!'
    });

    const map = new google.maps.Map(this.gmap.nativeElement, mapOptions);
    marker.setMap(map);
  }
}