Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Directions service #495

Closed
ramnes opened this issue Jul 8, 2016 · 54 comments
Closed

Directions service #495

ramnes opened this issue Jul 8, 2016 · 54 comments
Labels

Comments

@ramnes
Copy link

ramnes commented Jul 8, 2016

Hi,

Do you have any plan to support the directions service?

@christophechevalier
Copy link

Same question for me ..

Can we use the directions service with angular2-google-maps ?

-> directions service
-> example

Thank you very much for your work
-- Chris

@amourinho
Copy link

I too would like to know if this is something I can access. I'm working on a rather map heavy project that requires one of the maps to show Google's suggested directions between two locations. Please let me know if I've over looked the documentation and just not found it. Either way, this project is fantastic! Thanks for your work @SebastianM

@davidpestana
Copy link

This directive can solve your needs

import {GoogleMapsAPIWrapper} from 'angular2-google-maps/core/services/google-maps-api-wrapper';
import { Directive,  Input} from '@angular/core';
declare var google: any;



@Directive({
  selector: 'sebm-google-map-directions'
})
export class DirectionsMapDirective {
  @Input() origin;
  @Input() destination;
  constructor (private gmapsApi: GoogleMapsAPIWrapper) {}
  ngOnInit(){
    this.gmapsApi.getNativeMap().then(map => {
              var directionsService = new google.maps.DirectionsService;
              var directionsDisplay = new google.maps.DirectionsRenderer;
              directionsDisplay.setMap(map);
              directionsService.route({
                      origin: {lat: this.origin.latitude, lng: this.origin.longitude},
                      destination: {lat: this.destination.latitude, lng: this.destination.longitude},
                      waypoints: [],
                      optimizeWaypoints: true,
                      travelMode: 'DRIVING'
                    }, function(response, status) {
                                if (status === 'OK') {
                                  directionsDisplay.setDirections(response);
                                } else {
                                  window.alert('Directions request failed due to ' + status);
                                }
              });

    });
  }
}

@ahardworker
Copy link

hey david, thanks for the directive, but i'm having a hard time including it in my code. Should I insert it right in the google map dom. For instance:
<sebm-google-map sebm-google-map-directions [origin=x] [destination=y][zoomControl]="false" [latitude]="lat" [longitude]="lng" (mapClick)="mapClicked($event)"> </sebm-google-map>

I'm having a hard time making it work, I'm actually really new to angular 2... thanks for your help

@davidpestana
Copy link

davidpestana commented Nov 22, 2016

Hi @ahardworker , This is the right way:

<sebm-google-map>
  <sebm-google-map-directions [origin]="origin" [destination]="destination"></sebm-google-map-directions>
</sebm-google-map>

in your component controller class you must be define this properties.

origin = { longitude: 4.333, lattitude: -1.2222 };  // its a example aleatory position
destination = { longitude: 22.311, lattitude: -0.123 };  // its a example aleatory position

@ahardworker
Copy link

ahardworker commented Nov 22, 2016

Thanks! Its working. But I wonder is it possible to dynamically add waypoints, then update the direction without refreshing the page?

Actually here is what I got :
I added to my component :

@ViewChild(DirectionsMapDirective) vc:DirectionsMapDirective;
and then I simply call vc.updateDirections() from the component whenever a new waypoint is added. Which will call back the code in the directive. Is it the right way to do it?

@davidpestana
Copy link

davidpestana commented Nov 23, 2016

Sure @ahardworker, waypoints is Array of positions, you can add logic at the directive or inject this array using a input parameter.

for example...

<sebm-google-map>
  <sebm-google-map-directions [origin]="origin" [destination]="destination" [waypoints]="waypoints"></sebm-google-map-directions>
</sebm-google-map>

Directive:

@Directive({
  selector: 'sebm-google-map-directions'
})
export class DirectionsMapDirective {
  @Input() origin;
  @Input() destination;
  @Input() waypoits;
  constructor (private gmapsApi: GoogleMapsAPIWrapper) {}
  ngOnInit(){
    this.gmapsApi.getNativeMap().then(map => {
              var directionsService = new google.maps.DirectionsService;
              var directionsDisplay = new google.maps.DirectionsRenderer;
              directionsDisplay.setMap(map);
              directionsService.route({
                      origin: {lat: this.origin.latitude, lng: this.origin.longitude},
                      destination: {lat: this.destination.latitude, lng: this.destination.longitude},
                      waypoints: waypoints,
                      optimizeWaypoints: true,
                      travelMode: 'DRIVING'
                    }, function(response, status) {
                                if (status === 'OK') {
                                  directionsDisplay.setDirections(response);
                                } else {
                                  window.alert('Directions request failed due to ' + status);
                                }
              });

    });
  }
}

@bene-starzengruber
Copy link

bene-starzengruber commented Nov 28, 2016

Hello @davidpestana
I tried to include the Directions-Directive but I'm getting this error:
Can't bind to 'origin' since it isn't a known property of 'sebm-google-map-directions'.

(I don't know, why the formatting is that bad but I hope you manage to read it anyway)

HTML
<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom"> <sebm-google-map-marker [latitude]="latHome" [longitude]="lngHome" [title]="'titleHome'"</sebm-google-map-marker> <sebm-google-map-marker [latitude]="latComp" [longitude]="lngComp" [title]="titleComp"</sebm-google-map-marker> <sebm-google-map-directions [origin]="origin" [destination]="destination"></sebm-google-map-directions> </sebm-google-map>

Component
`@Component({
selector: 'google-maps',
styles: [require('./googleMaps.scss')],
template: require('./googleMaps.html'),
})
export class GoogleMaps {
latHome: number = 48.151839;
lngHome: number = 13.831726;
latComp: number = 48.329500;
lngComp: number = 14.319765;
titleComp: string = "dynatrace";
zoom: number = 10;

lat: number = (this.latComp + this.latHome) / 2;
lng: number = (this.lngComp + this.lngHome) / 2;

origin = { longitude: 4.333, lattitude: -1.2222 };
destination = { longitude: 22.311, lattitude: -0.123 };
}`

Do I have to register the directive somewhere?

@lazarljubenovic
Copy link
Collaborator

@ProkerBen Yes, you need to register the directive in the module you're using it as a declaration, just like any other directive you use.

@davidpestana
Copy link

davidpestana commented Nov 29, 2016

Yes @ProkerBen, how @lazarljubenovic saids ,you must need register the directive in your module

import { CustomMapDirective } from '[your route to directive folder]/google-map.directive';
...
@NgModule({
  imports: [...],
  exports: [..],
  declarations:[...,CustomMapDirective]
})

@nhtua
Copy link

nhtua commented Nov 29, 2016

@davidpestana DirectionsMapDirective displays the route but It doesn't zoom-in although I had set zoom=17

@davidpestana
Copy link

its a google api property, when using DirectionsDisplayService, map automaticly zooms in order to view all waypoints. if you set a Zoom Value,it will be ignored.

@nhtua
Copy link

nhtua commented Nov 29, 2016

@davidpestana ya! I tried the pure func of GMapSDK and it works well.

}, function(response, status) {
  if (status === 'OK') {
    directionsDisplay.setOptions({ preserveViewport: true });
    directionsDisplay.setDirections(response);
  } else {
    window.alert('Directions request failed due to ' + status);
  }

directionsDisplay.setOptions({ preserveViewport: true }) force the map keeps zoom value

@okanok
Copy link

okanok commented Dec 2, 2016

@davidpestana Hi,

I have a problem with the API. I use the directive like you showed in this thread and it works very good!
The only problem I have is when I need to show a new route on the same map. I call the same function again from the parent Component and it prints the new route over the old one. This is the code i have:
`
export class DirectionsMapDirective {
@input() destination:string;
@input() origin:string;

constructor (private gmapsApi: GoogleMapsAPIWrapper) {

}

ngOnInit(){
    this.setMap();
}

setMap():void{
    this.gmapsApi.getNativeMap().then(map => {
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer({draggable: true});
        directionsDisplay.setMap(map);
        directionsService.route({
            origin: this.origin,
            destination: this.destination,
            waypoints: [],
            optimizeWaypoints: true,
            travelMode: 'DRIVING'
        }, function(response, status) {
            if (status === 'OK') {
                directionsDisplay.setDirections(response);
            } else {
                window.alert('Directions request failed due to ' + status);
            }
        });

    });
}

}
`
When i need to show the new route the parent component calls the setMap function and the origin and destination variables change.
Is there a way to reload the map from the parent Component?

@drewlavine
Copy link

drewlavine commented Jan 11, 2017

@davidpestana I too am having the issue described by okanok. If anyone has a fix for the map displaying all routes without resetting it would be very helpful.
@okanok did you ever get this figured out

@developernm
Copy link

developernm commented Jan 13, 2017

Hi @davidpestana and @ahardworker, I tried to use the directive and the HTML david specified but i keep getting this error "InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: in property lat: not a number; and unknown property lat".

Component.ts
origin = { longitude: 4.333, lattitude: -1.2222 }; // its a example aleatory position
destination = { longitude: 22.311, lattitude: -0.123 }; // its a example aleatory position

Component.html

<sebm-google-map-directions [origin]="origin" [destination]="destination"></sebm-google-map-directions>

Error : InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: in property lat: not a number; and unknown property lat

Do you have any idea's please?

thanks

@bene-starzengruber
Copy link

bene-starzengruber commented Jan 13, 2017

@developernm you spelled latitude wrong ;)

@developernm
Copy link

@bene-starzengruber was in a little bit in a rush lol

@bonzysalesman
Copy link

I have been following this topic with great interest. And I look forward to this being integrated into the project (core).

@figuerres
Copy link

I am also intetesTed I need having the route planning and directions api.

@marimuthum17
Copy link

@davidpestana @ahardworker Have implemented the Map with Directions. But I am getting multiple Directions. Have attached my Map Route. Can you please suggest How to get single route at each time?.

Each time Destionation Value change I will call My DirectionsMapDirective Directive.

Thanks in advance.

screen shot 2017-01-18 at 6 29 22 pm

@pzuschlag
Copy link

pzuschlag commented Jan 18, 2017

@okanok @marimuthum17,
After hours of trying i think i got a workaround for this problem... In here you can read that it is necessary to define directionsDisplay global. By defining directionsDisplay inside the directive, each time will create a new instance of DirectionRenderer and so it can't remove the previous route.

So I create DirectionRenderer in my component.
if(this.directionsDisplay === undefined){ this.mapsAPILoader.load().then(() => { this.directionsDisplay = new google.maps.DirectionsRenderer; this.showDirective = true; }); }

And then inject it with @Input() directionsDisplay; into your directive.

I think that isn't fine.. but it works..

@marimuthum17
Copy link

marimuthum17 commented Jan 19, 2017

@zuschy You have done a GREAT JOB. It works like a charm!!. Thanks for you help.

The change what I did is : @input() directionsDisplay: any; // Have added type for an input.

You saved my day.

@bonzysalesman
Copy link

Can someone be so kind as to write this as an example to be incorporated into the project?

@Giusti
Copy link

Giusti commented Feb 5, 2017

@zuschy, @marimuthum17
I tried to send the directionsDisplay to the directive via input like this but the directionsDisplay is always undefined in the directive

<sebm-google-map-directions *ngIf="marker_count > 1" [directionsDisplay]="directionsDisplay" [waypointCnt]="waypointCnt" [origin]="origin" [destination]="destination" [waypoints]="waypoints"></sebm-google-map-directions>

in the Component I do this

 ngOnInit() {
        this.searchControl = new FormControl();
        this.setCurrentPosition();
        if(this.directionsDisplay === undefined){
            this.gmapsApi.getNativeMap().then(map => {               
                this.directionsDisplay = new google.maps.DirectionsRenderer({
                    draggable: true,
                    map: map,
                });
            });
        }

and in the directive

@Input() directionsDisplay;

ngOnChanges(changes: SimpleChanges) {
        console.log('onChange fired');
        console.log('changing', changes);
        this.gmapsApi.getNativeMap().then(map => {
            var directionsService = new google.maps.DirectionsService;
            this.directionsDisplay.addListener('directions_changed', function() {
                computeTotalDistance(this.directionsDisplay.getDirections());
            });

            this.directionsDisplay.setMap(map);
            directionsService.route({
                origin: {lat: this.origin.latitude, lng: this.origin.longitude},
                destination: {lat: this.destination.latitude, lng: this.destination.longitude},
                waypoints: this.waypoints,
                optimizeWaypoints: true,
                travelMode: 'DRIVING'
            }, function(response, status) {
                if (status === 'OK') {
                    //directionsDisplay.setDirections({routes: []});
                    this.directionsDisplay.setDirections(response);
                } else {
                    window.alert('Directions request failed due to ' + status);
                }
            });

@manohar-nyros
Copy link

@zuschy @marimuthum17 @Giusti
Me too facing the same problem. directionsDisplay getting undefined in the directive.

@marimuthum17
Copy link

marimuthum17 commented Feb 6, 2017

@manohar-nyros @Giusti
Here how I have declared My Directive in Controller
@ViewChild(DirectionsMapDirective) vc: DirectionsMapDirective;
........ and accessed like beow.
if(this.vc.directionsDisplay === undefined){ this.mapsAPILoader.load().then(() => {
this.vc.directionsDisplay = new google.maps.DirectionsRenderer;
});

@marimuthum17
Copy link

marimuthum17 commented Feb 6, 2017

@bonzysalesman @Giusti @manohar-nyros
google-map-directions-display-in-angular-2

I have created google map directions service in angular 2 for one of my project.
Here have written one article about this, You can find full sorce code
Here have attached demo, If you want you can download the script also. Hope it will help someone else also.

@Giusti
Copy link

Giusti commented Feb 6, 2017

@marimuthum17
Thank you very much gonna take a look at it, another problem is, how would I add autocomplete fields in an ng-for lets say in your example you would have an + button and another searchfield would appear. since the searchfields have to be bound to the #pickupInput / #pickupoutput and has to have a @ViewChild ?

@manohar-nyros
Copy link

@marimuthum17
Thanks for the support. That works fine for me. Thanks a lot again.

@Giusti
Copy link

Giusti commented Feb 12, 2017

@marimuthum17, @zuschy
Hey the directive is working out great so far but I encountered another problem:

When the User drags am Marker from the generated Route and then adds a Marker to the Route the dragged marker jumps back to its starting point(because I call this.vc.updateDirections()) I think its because the origin in the component is not updated when I listend to the "directions_changed" in the directive.

I tried to create an @Output in the Directive but It seems I cant use origin as @Input and @Output
I also tried to place the listener in the ngOnInit in the Component where the directionsDisplay is created but somehow it gets undefined in the .addListener

And I am not sure what marker is dragged so my Idea was to create a switch case in the directions_changed Listener and check whether the requestOrigin is matching origin / destination or 1 of the waypoints

Heres my code

Directive

export class DirectionsMapDirective {
    // get variables from map.component
    @Input() origin;
    @Input() destination;
    @Input() waypoints;
    @Input() waypointCnt;
    @Input() directionsDisplay;

    constructor (private gmapsApi: GoogleMapsAPIWrapper) {}

    // updateDirections has 2 optional parameters. gets called in map.component
    updateDirections(directionsDisplay, o?, d?){
        this.gmapsApi.getNativeMap().then(map => {
            var directionsService = new google.maps.DirectionsService;
            directionsDisplay.addListener('directions_changed', function() {
                //this.vc.computeTotalDistance(this.directionsDisplay.getDirections());

                if(directionsDisplay && directionsDisplay.dragResult){
                    let requestOrigin = directionsDisplay.dragResult.request.origin;
                    let requestDestination = directionsDisplay.dragResult.request.destination;
                    console.log(this.origin)
                    if(this.origin && (requestOrigin.lat.toString() == this.origin.latitude && requestOrigin.lng.toString() == this.origin.longitude)){
                        console.log('if?');
                        let temp_lat = requestDestination.lat.toString();
                        let temp_lng = requestDestination.lng.toString();
                        this.origin.latitude = temp_lat;
                        this.origin.longitude = temp_lng;
                        this.vc.updateDirections(directionsDisplay);
                    }
                }
                console.log(directionsDisplay);
            });


            //if origin / destination are undefined use value from optional parameters.
            directionsDisplay.setMap(map);
            if(!this.destination && d) {
                this.destination = d;
            }
            if(!this.origin && o) {
                this.origin = o;
            }

            // give the route the data, travel mode is driving bc users should plan a camping/ roadtrip.
            directionsService.route({
                origin: {lat: this.origin.latitude, lng: this.origin.longitude},
                destination: {lat: this.destination.latitude, lng: this.destination.longitude},
                waypoints: this.waypoints,
                optimizeWaypoints: true,
                travelMode: 'DRIVING'
            }, function(response, status) {
                console.log(status);
                if(status == 'OK'){
                    console.log('new route created')
                    var legs = response.routes[0].legs;
                    for (var i = 0; i < legs.length; i++) {
                        let inputFieldStart = document.getElementById('start') as HTMLInputElement;
                        let inputFieldDestination = document.getElementById('destination') as HTMLInputElement;
                        if(inputFieldStart.value == ''){
                            inputFieldStart.value = legs[i].start_address;
                        }
                        if(inputFieldDestination.value == ''){
                            inputFieldDestination.value = legs[i].end_address;
                        }
                    }
                    if (status === 'OK') {
                        directionsDisplay.setDirections(response);
                    } else {
                        window.alert('Directions request failed due to ' + status);
                    }
                }else{
                    console.log('keine Route möglich!')
                }
            });

            //function for displaying the travel distance
            function computeTotalDistance(result) {
                var total = 0;
                var myroute = result.routes[0];
                for (var i = 0; i < myroute.legs.length; i++) {
                    total += myroute.legs[i].distance.value;
                }
                total = total / 1000;
                document.getElementById('trip_length').innerHTML = 'The trip is <span id="trip_length_nr">' +total + '</span>km long.';
            }
        });
    }
}

Component:

Here I basically call this.vc.updateDirections(this.directionsDisplay); on Mapclicked / Autocomplete

When I tried the Listener here like this: (the first if after addListener directionsDisplay = undefined)

ngOnInit() {


        this.searchControl = new FormControl();

        this.setCurrentPosition();

        this.mapsAPILoader.load().then(() => {
            this.geocoder = new google.maps.Geocoder;
            this.directionsDisplay = new google.maps.DirectionsRenderer({draggable: true});
            this.directionsDisplay.addListener('directions_changed', function() {
                //directionsDisplay = undefined?????
                if(this.directionsDisplay && this.directionsDisplay.dragResult){
                    let requestOrigin = this.directionsDisplay.dragResult.request.origin;
                    let requestDestination = this.directionsDisplay.dragResult.request.destination;
                    console.log(this.origin)
                    if(this.origin && (requestOrigin.lat.toString() == this.origin.latitude && requestOrigin.lng.toString() == this.origin.longitude)){
                        console.log('if?');
                        let temp_lat = requestDestination.lat.toString();
                        let temp_lng = requestDestination.lng.toString();
                        this.origin.latitude = temp_lat;
                        this.origin.longitude = temp_lng;
                        this.vc.updateDirections(this.directionsDisplay);
                    }
                }
                console.log(this.directionsDisplay);
            });
            let autocomplete = new google.maps.places.Autocomplete(this.OriginSearchElementRef.nativeElement, {
                types: ["address"]
            });
            let autocomplete2 = new google.maps.places.Autocomplete(this.DestinationSearchElementRef.nativeElement, {
                types: ["address"]
            });
            let autocomplete3 = new google.maps.places.Autocomplete(this.WaypointSearchElementRef.nativeElement, {
                types: ["address"]
            });

            autocomplete.addListener("place_changed", () => {
                this.addAutocomplete(autocomplete, 'origin');
            });
            autocomplete2.addListener("place_changed", () => {
                this.addAutocomplete(autocomplete2, 'destination');
                this.vc.updateDirections(this.directionsDisplay);
            });
            autocomplete3.addListener("place_changed", () => {
                this.addAutocomplete(autocomplete3, 'waypoint');
                this.vc.updateDirections(this.directionsDisplay);
            });

        });

    }

@nccmike
Copy link

nccmike commented Feb 20, 2017

Question:

Currently subscribing to list in database. I am using ngFor to create and remove markers when they are added or deleted from database. Is there a way I can associate directions with particular markers and then remove the directions when the marker is removed from the map?

Basically, user says they are available in app. Marker shows up on map with directions to location. When they say they are unavailable. I want the marker and directions associated with it removed from map.

I also watch the location of user with watchPosition. Obviously want marker position updated as well as directions.

@srajabhoj
Copy link

@davidpestana thank you for such brilliant work... i implemented basic directive but it giving me error "Directions request failed due to ZERO_RESULTS" can please help me with this error?

@MartiniHenry1988
Copy link

I am also facing this issue please check this :

#985

@marimuthum17
Copy link

Thats nothing wrong with code.
Please check, you have added your google map key while calling api. or As per google docs there is cetain limit request for every day.

@srajabhoj
Copy link

@marimuthum17 you are correct there was nothing wrong in your code... Actually I missed part of placeId... I was not providing placeId correctly, that was the issue...

@MartiniHenry1988 you are getting problem because you are not using direction service of google....please refer @marimuthum17 's earlier comment for complete example.

@chaoranxie
Copy link

chaoranxie commented Jun 30, 2017

did anyting change?, i am getting error below on line directionsDisplay.setMap(map);

Argument of type 'GoogleMap' is not assignable to parameter of type 'Map'

@kildareflare @amitdahan i see that you guys might have encountered the same issue, did you ever found a fix?

@rvaitkus23
Copy link

I am facing this issue as well. @chaoranxie have you found solution?

@Fabian-Luque
Copy link

Sorry, I know the subject is already a bit old but I'm having problems and this is the error:
Can't bind to 'origin' since it isn't a known property of 'sebm-google-map-directions'.
but above gave a solution and I'm not clear how to do it, could someone give me an example?

Sorry for my bad english

@Acap72
Copy link

Acap72 commented Oct 17, 2017

@Fabian-Thug what version of Angular are you using? I am on 4* and directives work differently.
In the Directive change the syntax from selector: 'sebm-google-map-directions' to selector ['sebm-google-map-directions'] then in the HTML add it TO an element instead of AS an element (example <div sebm-google-map-directions [origin]="origin" [destination]="destination"

I am having issues with the autocomplete event listener and will likely rewrite it with a button. (Using @marimuthum17 code example - which is not working on his site but I think the issue is with the events.

[UPDATE]
Change this:
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
To this:
const place = autocomplete.getPlace();

@karthikeyanmanureva
Copy link

karthikeyanmanureva commented Oct 25, 2017

@davidpestana @marimuthum17 I have done the above one. Now it shows the direction between user's current location and selected destination.
But I need to change marker icons! How to do that?
How to include custom markers in the direction result?

@debashishdwivedi1
Copy link

@davidpestana
you give this solution import { CustomMapDirective } from '[your route to directive folder]/google-map.directive'; but for this do i need to install some package ??

@pranavsreedhar92
Copy link

Getting an ERROR TypeError: Cannot set property 'origin' of undefined.

@ViewChild(DirectionsMapDirective) vc: DirectionsMapDirective;
public origin :any ;
public destination : any;
constructor(
private modalService : NgbModal,

private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone,
private gmapsApi: GoogleMapsAPIWrapper,
private _elementRef : ElementRef

) {}

Passing values
this.vc.origin = { longitude: 77.333, latitude: 12.2222 };
this.vc.destination = { longitude: 90.311, latitude: 28.123 };
this.vc.updateDirections();

Thanks in advance.

@SivaPrasanna45
Copy link

i have two points in my map , how can i get directions between them?
component.ts

import { Component } from '@angular/core';
import { MouseEvent } from '@agm/core';

@component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
zoom: number = 8;

lat: number = 51.673858;
lng: number = 7.815982;

markers: marker[] = [
{
lat: 51.673858,
lng: 7.815982,
label: 'A',
draggable: true
},
{
lat: 51.373858,
lng: 7.215982,
label: 'B',
draggable: false
}
]

}

interface marker {
lat: number;
lng: number;
label?: string;
draggable: boolean;
}

@SivaPrasanna45
Copy link

SivaPrasanna45 commented Jan 10, 2018

@davidpestana when i am trying to use your code i am getting error like
"Can't bind to 'origin' since it isn't a known property of 'sebm-google-map-directions"

  1. If 'sebm-google-map-directions' is an Angular component and it has 'origin' input, then verify that it is part of this module.
  2. If 'sebm-google-map-directions' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
  3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

@ghost
Copy link

ghost commented Jan 21, 2018

@davidpestana Might be worth noting your waypoints can be defined as a response from the places API, LatLng, or like:

let waypoints = [
    {location: {placeId: place_id}}
];

https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests

This all worked for me, thank you! Would this be worth adding to agm/core if it was in the same format as the other directives?

@rochapablo
Copy link

Is there any update about this?

Is it possible use origin and destination as string?

@yongbin999
Copy link

yongbin999 commented Feb 7, 2018

the reason you cannot access the estimate time & distance is because this code block below. This is an anonymous callback function, where it doesn't have access read/write the class's this.xyz variables.
}, function(response: any, status: any) {

i was able to store the info and use services inside that function after i changed to below. it uses es6 arrow function which native to typescript classes. more info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
}, (response: any, status: any) => {

@NOVAXamarin
Copy link

Hello,
Can someone show me how to create event such as click start location as output in a route of the direction-path.

Thanks

@ghost
Copy link

ghost commented May 11, 2018

Hi @davidpestana , @marimuthum17 , @okanok

I am facing a new problem like, when I draw route for the first time, it displays correctly , If I am trying to draw another route, the first one is not getting cleared and for new route, the line is not getting displayed.

Here is my code,

component.ts,

showDirections( ) { if ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition((position) => { this.org = { latitude: position.coords.latitude, longitude: position.coords.longitude}; this.dst = {longitude: this.cycle.longitude, latitude: this.cycle.latitude}; console.log('Src ' + this.org.latitude ); console.log('Dst' + this.dst.latitude ); }); } }

This function is called after clicking a button by the user. and component's html,
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom"> <appCycleDirection *ngIf="dst !== undefined" [org]="org" [dst]="dst"></appCycleDirection> <agm-marker [style.height.px]="map.offsetHeight" [latitude]="lat" [longitude]="lng"></agm-marker> </agm-map>

The directive code is as follows,

import { Directive, Input, OnInit } from '@angular/core';
import {GoogleMapsAPIWrapper} from '@agm/core';

declare let google: any;
@Directive({
  // tslint:disable-next-line:directive-selector
  selector: 'appCycleDirection'
})
export class CycleDirectionDirective implements OnInit {

  @Input() org;
  @Input() dst;
  @Input() originPlaceId: any;
  @Input() destinationPlaceId: any;
  @Input() waypoints: any;
  @Input() directionsDisplay: any;
  @Input() estimatedTime: any;
  @Input() estimatedDistance: any;
  constructor(private gmapsApi: GoogleMapsAPIWrapper) { }

  ngOnInit() {
    console.log(' In directive ');
    console.log(this.org);
    this.gmapsApi.getNativeMap().then(map => {
      const directionsService = new google.maps.DirectionsService;
      const directionsDisplay = new google.maps.DirectionsRenderer;
      directionsDisplay.setMap(map);
      directionsService.route({
              origin: {lat: this.org.latitude, lng: this.org.longitude},
              destination: {lat: this.dst.latitude, lng: this.dst.longitude},
              waypoints: [],
              optimizeWaypoints: true,
              travelMode: 'TRANSIT'
            }, function(response, status) {
                        if (status === 'OK') {
                          directionsDisplay.setDirections(response);
                          console.log(response);
                        } else {
                          window.alert('Directions request failed due to ' + status);
                        }
      });

    });
  }

}

```

What is wrong with my code , I want to make disappear of first route when new route is displayed.

@Mihajarivelo
Copy link

Mihajarivelo commented Jul 2, 2018

Hi, can we put a click event on the road?
Thanks

@patelmurtuza
Copy link

I have used the same directive in my project and it works fine, Just a quick question, Is it possible to display traffic (red, yellow or blue sections on line) on road like in Waze, Uber or lyft driving maps?
your help is highly appreciated

@manunoly
Copy link

This guy has done an excellent job with this directive, I have tried it and it works very well, please consider if it can be included in AGM.

https://github.com/explooosion/Agm-Direction

routewithagm

@stale
Copy link

stale bot commented Jan 9, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale label Jan 9, 2019
@stale stale bot closed this as completed Jan 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests