1

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.

4
  • Not sure if this is the issue, depends on how you load the map at runtime, but import { } from 'googlemaps'; is suspicious code. Commented Dec 1, 2017 at 7:20
  • @AluanHaddad can you be more clear please , in what way is it suspicious? Should i do it in some other way ? I actually can see that the entire code runs smooth with no compile/run time errors and the response looks perfect . Probably I am doing something wrong with the maps rendering part during the runtime which is what I wanted to know Commented Dec 1, 2017 at 9:05
  • I don't think what I mentioned was the issue if everything is loading correctly. Commented Dec 1, 2017 at 9:07
  • Hi @Bhavya, is it possible for you to tell how u made it work? I am running into the same issue. Thanks Commented Feb 2, 2018 at 14:00

2 Answers 2

1

You should take a look @ https://angular-maps.com/ it is a great component module to use Google Maps with Angular

Sample from their Page

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 {}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Rahul , thanks for the quick response . They do not support direction feature right now.
0

Finally I managed to render them map by making two changes :

  1. Move mapView element out of app-card . So now my html file 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> </app-card>
    <div id='mapView' #mapView></div> </div>

  2. Set width and height to 100% for the mapView element inside the css file

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.