Home:ALL Converter>Google Maps directions implementation using Typescript and Angular 4

Google Maps directions implementation using Typescript and Angular 4

Ask Time:2017-12-01T14:51:09         Author:Bhavya Latha Bandaru

Json Formatter

I am pretty new to front end development and Angular 4.

I tried to implement the Google Places AutoComplete and Google Maps Directions using Typescript in Angular 4.

I haven't used any third party libraries and I tried to use the example code from Google's official documentation (Demos and Sample code > DIRECTIONS)

My component code looks like below:

NOTE: I have hardcoded the destination, while the source is picked up from the autocomplete field.

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)}
      });

    })
  }

}

My html code looks like this:

<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>

Now the actual issue is that the map never gets displayed, the component code used to generate directions works fine (confirmed it from console.logs). There is no error either, but the map is never shown on the html page.

enter image description here

Can someone help me out as of where did I go wrong or did I miss anything required for rendering.

Thanks in advance.

Author:Bhavya Latha Bandaru,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/47588058/google-maps-directions-implementation-using-typescript-and-angular-4
Rahul Singh :

You should take a look @ https://angular-maps.com/ it is a great component module to use Google Maps with Angular\n\nSample from their Page\n\nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule, Component } from '@angular/core';\n\nimport { AgmCoreModule } from '@agm/core';\n\n@Component({\n selector: 'app-root',\n styles: [`\n agm-map {\n height: 300px;\n }\n `],\n template: `\n <agm-map [latitude]=\"lat\" [longitude]=\"lng\"></agm-map>\n `\n})\nexport class AppComponent {\n lat: number = 51.678418;\n lng: number = 7.809007;\n}\n\n@NgModule({\n imports: [\n BrowserModule,\n AgmCoreModule.forRoot({\n apiKey: 'YOUR_GOOGLE_MAPS_API_KEY'\n })\n ],\n declarations: [ AppComponent ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule {}\n",
2017-12-01T07:01:42
yy