Angular 2 google map implementation

前端 未结 1 1123
无人及你
无人及你 2021-02-08 22:49

I\'m new to angular 2. I wanted to use google map API for direction service and implemented the example shown in https://developers.google.com/maps/documentation/javascript/exam

相关标签:
1条回答
  • 2021-02-08 23:39

    Found a solution for this.

    1) Add google map api script in index.html

    index.html

    <script src="https://maps.googleapis.com/maps/api/js?key=[YOUR-KEY]" async defer></script>
    

    2) Add only html related code in your html file.

    map.html

    <div id="map"></div>
    

    3) Add style related codes in separate css file or in component.

    map.css

          #map {
            height: 500px;
          }
    

    4) Declare google as variable. And add all javascript in ngOnInit() method.

    MapComponent.ts

    declare var google: any;
    
    @Component({
        selector: 'map',
        templateUrl: 'app/dashboard/features/map.html',
        styleUrls: ['app/dashboard/features/map.css']
    }) 
    
    export class MapComponent implements OnInit, OnChanges {
    
    ngOnInit() {
    
            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);
            calculateAndDisplayRoute(directionsService, directionsDisplay);
    
          function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    
              var waypts = [];
              var checkboxArray:any[] = [
                  'winnipeg', 'regina','calgary'
          ];
          for (var i = 0; i < checkboxArray.length; i++) {
    
                waypts.push({
                  location: checkboxArray[i],
                  stopover: true
                });
    
            }
    
            directionsService.route({
              origin: {lat: 41.85, lng: -87.65},
              destination: {lat: 49.3, lng: -123.12},
              waypoints: waypts,
              optimizeWaypoints: true,
              travelMode: 'DRIVING'
            }, function(response, status) {
              if (status === 'OK') {
                directionsDisplay.setDirections(response);
              } else {
                window.alert('Directions request failed due to ' + status);
              }
            });
          }
    
        }
    
    0 讨论(0)
提交回复
热议问题