如何在HTTPGET(角度6)上向Google Maps组件动态添加标记

时间:2018-11-29 19:45:38

标签: angular typescript rest google-maps

我正在使用AGM通过Google Javascript API集成构建Angular 6应用程序。该地图有效,除了可以使用http get动态添加标记。

这是component.html

<agm-map [latitude]="51.017467" [longitude]="10.233982">
    <agm-marker *ngFor="let position of positions" [latitude]="position.latitude"
                [longitude]="position.longitude"></agm-marker>
</agm-map>

还有component.ts

export class EventsListComponent {
 public positions = [new Position(51.017467, 10.233982)]; // static point for debug

 constructor(public http: HttpClient) {
  let eventIds: string[] = ['5bffbac5596a7de59190dfbb']; // also for debug
  for (let eventId of eventIds) {
    this.http.get<Address>("api/v1/Events/Get/" + eventId +"/GetVenue/GetAddress").subscribe(result => {
      console.log(result);
      this.addresses.push(result);
    });
  }
}

export class Address {

  constructor(
    public latitude: number,
    public longitude: number,
    public addressLine: string,
    public city: string,
    public state: string,
    public country: string,
    public zip) {
  }
}

这将打印到控制台:

{
"addressLine":"Gartenstraße 7",
"city":"Eschwege",
"country":"Germany",
"zip":"37269",
"state":"Hessen",
"latitude":"51.1821073",
"longitude":"10.0572713"
}

产生以下结果:

Adding marker with REST

标记显示在DOM中,而不显示在地图上(您看到的标记是静态标记,应该是两个)。

我尝试过的其他事情:

动态添加标记可通过如下方式按下按钮:

<button (click)="btnClick()" class="btn btn-primary"></button>

然后在component.ts中:

btnClick() {
    this.addresses.push(new Address(51.1821073, 10.0572713,"","","","",""));
}

产生以下结果:

Adding marker with button

标记显示在地图上的DOM 中。

我尝试过的其他事情(pt2):

将http get请求放入按按钮的调用方法中,如下所示:

btnClick() {
    this.http.get<Address>("api/v1/Events/Get/" + eventId +"/GetVenue/GetAddress").subscribe(result => {
    console.log(result);
    this.addresses.push(result);
  });
}

它仍然仅将标记添加到dom,而不添加到地图。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我认为您在使用服务调用时将lat / lng作为字符串传递(如控制台日志中的""所示),但在手动添加时将其作为数字传递它。尝试做这样的事情

this.addresses.push({
  addressLine: result.addressLine,
  city: result.city,
  country: result.country,
  zip: result.zip,
  state: result.state,
  latitude: +result.latitude,
  longitude: +result.longitude
});

或者您可以尝试将其缩短为类似的内容

result.latitude = +result.latitude;
result.longitude = +result.longitude;
this.addresses.push(result);