2017-04-05 35 views

回答

0

有你加入應該包含地圖的div的寬度和高度。請找到我編寫的下面的map指令,根據需要重新使用和修改。

它可用於像,

<map trip="latLongObj" on-create="controllerFunction()"></map>

和定義,

function map($window) { 
    return { 
     restrict: 'E', 
     scope: { 
      onCreate: '&', 
      trip: '=', 
      location: '@' 
     }, 
     link: function ($scope, $element) { 

      var DirectionsDisplay; 
      var DirectionsService = new google.maps.DirectionsService(); 

      function initialize(trip) { 
       DirectionsDisplay = new google.maps.DirectionsRenderer(); 

       var origin = {}, destin = {}; 

       if (!$scope.location) { 
        origin.lat = trip.origin.latitude; 
        origin.long = trip.origin.longitude; 

        destin.lat = trip.destination.latitude; 
        destin.long = trip.destination.longitude; 
       } else { 
        origin.lat = trip.location.latitude; 
        origin.long = trip.location.longitude; 
       } 

       var mapOptions = { 
        center: new google.maps.LatLng(origin.lat, origin.long), 
        zoom: 13, 
        mapTypeId: google.maps.MapTypeId.ROADMAP, 
        mapTypeControl: false, 
        streetViewControl: false 
       }; 


       var map = new google.maps.Map($element[0], mapOptions); 

       if (!$scope.location) { 
        DirectionsDisplay.setMap(map); 
        DirectionsService.route({ 
         origin: new google.maps.LatLng(origin.lat, origin.long), 
         destination: new google.maps.LatLng(destin.lat, destin.long), 
         travelMode: google.maps.TravelMode.DRIVING 
        }, function (response, status) { 
         if (status === google.maps.DirectionsStatus.OK) { 
          DirectionsDisplay.setDirections(response); 
         } else { 
          $window.alert('Directions request failed due to ' + status); 
         } 
        }); 
       } 

       $scope.onCreate({ map: map }); 
      } 

      $scope.$watch('trip', function (trip) { 
       if (trip) { 
        initialize(trip); 
       } 
      }, true) 
     } 
    } 
} 

可以acheive,而無需一個觀察者,並採用NG-如果在使用該指令確保有數據。