0

I'm using Angular 6 to implement a google maps based app with google maps direction API. I used following initial code in my project. But when ng serve, it says Cannot find name 'calculateAndDisplayRoute'.

I already tried with declare the function name 'calculateAndDisplayRoute' as commented above the class but seems not working either.

What is the problem here?

import { Component, OnInit } from '@angular/core';
declare var google: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['../../resources/css/style.min.css', '../../resources/css/bt.min.css']
})

// declare var calculateAndDisplayRoute(directionsService, directionsDisplay) : any;

export class HomeComponent implements OnInit {

    initMap() {
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 7,
            center: {lat: 41.85, lng: -87.65}
        });
        directionsDisplay.setMap(map);

        var onChangeHandler = function() {
            calculateAndDisplayRoute(directionsService, directionsDisplay);
        };
        document.getElementById('start').addEventListener('change', onChangeHandler);
        document.getElementById('end').addEventListener('change', onChangeHandler);
    }

    calculateAndDisplayRoute(directionsService, directionsDisplay) {
        directionsService.route({
            origin: (<HTMLInputElement>document.getElementById('start')).value,
            destination: (<HTMLInputElement>document.getElementById('end')).value,
            travelMode: 'DRIVING'
        }, function(response, status) {
            if (status === 'OK') {
                directionsDisplay.setDirections(response);
            } 
            else {
                window.alert('Directions request failed due to ' + status);
            }
        });
    }

    constructor() {

    }

    ngOnInit() {
        this.initMap();
    }

}
1
  • 1
    You have to call the function as this.calculateAndDisplayRoute(directionsService, directionsDisplay); Commented Dec 31, 2018 at 12:23

1 Answer 1

1

You should be using arrow function in typescript

var onChangeHandler = () => {
            calculateAndDisplayRoute(directionsService, directionsDisplay);
        };
Sign up to request clarification or add additional context in comments.

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.