Google使用typescript和angular 4映射路线实施

时间:2017-12-01 06:51:09

标签: javascript angular google-maps typescript

我对前端开发和角度4都很陌生。

我尝试使用角度4中的类型脚本实现Google地方自动完成和谷歌地图方向。

我没有使用任何第三方库,我尝试使用谷歌官方文档中的示例代码 https://developers.google.com/maps/documentation/javascript/ (演示和示例代码> DIRECTIONS)

我的组件代码如下所示:

注意:我已对目的地进行了硬编码,而从自动填充字段

中选择了源
import { Component, OnInit , ViewChild,ElementRef } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { } from 'googlemaps';

@Component({
  selector: 'app-plan-routes',
  templateUrl: './plan-routes.component.html',
  styleUrls: ['./plan-routes.component.css']
})
export class PlanRoutesComponent implements OnInit {
  place: google.maps.places.PlaceResult;
  public srcLatitude: number;
  public srcLongitude: number;
  public searchControl: FormControl;

  @ViewChild("source")
  public sourceElementRef: ElementRef;

  @ViewChild("mapView")
  public mapElementRef: ElementRef;

  constructor() { }

  ngOnInit() {
    this.srcLatitude = 39.8282;
    this.srcLongitude = -98.5795;
    var chicago = {lat: 41.85, lng: -87.65};
    var indianapolis = {lat: 39.79, lng: -86.14};
    this.searchControl = new FormControl()
    let source = new google.maps.places.Autocomplete(this.sourceElementRef.nativeElement, {
      type: "regions"
    });
    source.addListener("place_changed", () => {
      if(source.getPlace() != undefined){
        var src = source.getPlace().name
      } else {
        var src = 'delhi'
      }
      console.log("map : " +  this.mapElementRef.nativeElement)
      var map = new google.maps.Map(this.mapElementRef.nativeElement, {
        center: chicago,
        zoom: 7
      });

      var directionsDisplay = new google.maps.DirectionsRenderer({
        map: map
      });
      console.log("display : " + directionsDisplay.getMap().getCenter())

      // Set destination, origin and travel mode.
      var request : google.maps.DirectionsRequest = {
        destination: 'mumbai',
        origin: src,
        travelMode: google.maps.TravelMode.DRIVING
      };
      console.log("request : " + request.origin)

      // Pass the directions request to the directions service.
      var directionsService = new google.maps.DirectionsService();
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          // Display the route on the map.
          console.log("response : " + response.geocoded_waypoints.map(f => f.place_id))
          directionsDisplay.setDirections(response);        
        } else { console.log("not OK !" + status)}
      });

    })
  }

}

我的HTML代码如下所示:

<div class="row">
  <div class="col-sm-12">
    <app-card [title]="'Search stations anywhere in India'" >
      <div class="form-group">
        <input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #source>
      </div>
      <div>
        <div id='mapView' #mapView></div>
      </div>
    </app-card>
  </div>

现在实际问题是地图永远不会显示,用于生成路线的组件代码工作正常(从console.logs确认) 也没有错误,但地图永远不会显示在html页面上。

enter image description here

有人可以帮助我解决我出错的地方或者我错过了渲染所需的任何内容。

提前致谢。

2 个答案:

答案 0 :(得分:0)

你应该看看@ https://angular-maps.com/这是一个很棒的组件模块,可以使用带有Angular的Google地图

来自他们页面的样本

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Component } from '@angular/core';

import { AgmCoreModule } from '@agm/core';

@Component({
  selector: 'app-root',
  styles: [`
    agm-map {
      height: 300px;
    }
  `],
  template: `
  <agm-map [latitude]="lat" [longitude]="lng"></agm-map>
  `
})
export class AppComponent {
  lat: number = 51.678418;
  lng: number = 7.809007;
}

@NgModule({
  imports: [
    BrowserModule,
    AgmCoreModule.forRoot({
      apiKey: 'YOUR_GOOGLE_MAPS_API_KEY'
    })
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

答案 1 :(得分:0)

最后,我设法通过进行两处更改来渲染它们:

  1. 将mapView元素移出app-card。所以现在我的html文件看起来像这样:

    <div class="row"> <div class="col-sm-12"> <app-card [title]="'Search stations anywhere in India'" > <div class="form-group"> <input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #source> </div> </app-card>
    <div id='mapView' #mapView></div> </div>

  2. 将css文件中的mapView元素的宽度和高度设置为100%

    #mapView { width: 100%; height: 100%; }