map_route_planner-1.0.0-alpha4/js/google_map.js

js/google_map.js
(function(Drupal, drupalSettings){

  'use strict';

  console.log(drupalSettings.map_route);

  Drupal.behaviors.map_route = {
    toggleOverlay: function(action = 'show') {
      let overlay = document.getElementById('overlay');
      if (overlay) {
        if (action == 'hide') {
          overlay.classList.remove('show');
        }
        else {
          overlay.classList.add('show');
        }
      }
    }
  };
  Drupal.behaviors.google_map = {
    attach : function(context, settings) {
      window.initMap = Drupal.behaviors.google_map.initMap();
    },
    client_address_place: false,
    initMap: function() {
      let map_route = drupalSettings.map_route,
        $google_map = document.getElementById('google-map');
      Drupal.behaviors.map_route.toggleOverlay('show');
      let directionsDisplay, directionsService,
        lat = Number(map_route.map_settings_destination_address_lat),
        lng = Number(map_route.map_settings_destination_address_lng),
        transitLayer,// Property for road traffic.
        trafficLayer,// Property for public passenger transport traffic.
        map_data = {
          center: {
            lat: lat,
            lng: lng
          },
          zoom: map_route.map_settings_map_zoom_default_zoom,
          zoomControl: map_route.map_settings_map_zoom_zoom_control,
          scrollwheel: map_route.map_settings_map_zoom_zoom_scroll,
          mapTypeId: map_route.map_settings_map_type_map_type_default,
          mapTypeControl: map_route.map_settings_map_type_map_type_control,
          mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            mapTypeIds: map_route.map_settings_map_type_map_type_control_options,
          },
          scaleControl: map_route.map_other_map_controls_scale_control,
          fullscreenControl: map_route.map_other_map_controls_fullscreen_control,
          streetViewControl: map_route.map_other_map_controls_street_view_control,
          rotateControl: false
        };
      // @memo : I added true because it is possible to zoom in/out with the click.
      // @todo : Search for a control of the zoom click.
      if (map_route.map_settings_map_zoom_zoom_control || map_route.map_settings_map_zoom_zoom_scroll || true) {
        map_data.minZoom = map_route.map_settings_map_zoom_min_zoom;
        map_data.maxZoom = map_route.map_settings_map_zoom_max_zoom;
      }
      let map = new google.maps.Map($google_map, map_data);

      if (typeof map.name !== 'undefined' && map.name !== null && map.name == "InvalidValueError") {
        Drupal.behaviors.map_route.toggleOverlay('hide');
        console.log(map);
        window.alert('The loading of the card failed due to ' + map.message);
        return;
      }
      Drupal.behaviors.map_route.toggleOverlay('hide');

      let marker_data = {
        map: map,
        position: {
          lat: lat,
          lng: lng
        },
        opacity: Number(map_route.map_settings_marker_opacity)
      };

      if (map_route.map_settings_marker_enable_title) {
        marker_data.label = {};
        marker_data.label.text = map_route.map_settings_destination_address_title;
        if (map_route.map_settings_marker_override_default_style_title) {
          marker_data.label.fontSize = map_route.map_settings_marker_style_title_font_size;
          marker_data.label.fontWeight = map_route.map_settings_marker_style_title_font_weight;
          marker_data.label.color = map_route.map_settings_marker_style_title_color;
        }
      }

      if (map_route.map_settings_marker_override_default_svg) {
        // Example for the moment.
        let svgMarker = {
          path: "M10.453 14.016l6.563-6.609-1.406-1.406-5.156 5.203-2.063-2.109-1.406 1.406zM12 2.016q2.906 0 4.945 2.039t2.039 4.945q0 1.453-0.727 3.328t-1.758 3.516-2.039 3.070-1.711 2.273l-0.75 0.797q-0.281-0.328-0.75-0.867t-1.688-2.156-2.133-3.141-1.664-3.445-0.75-3.375q0-2.906 2.039-4.945t4.945-2.039z",
          fillColor: "blue",
          fillOpacity: 0.6,
          strokeWeight: 0,
          rotation: 0,
          scale: 2,
          anchor: new google.maps.Point(15, 30),
        };
        marker_data.icon = svgMarker;
      }
      let marker = new google.maps.Marker(marker_data);

      // Generate the InfoWindow on the marker click.
      if (map_route.map_settings_marker_enable_window_description) {
        let infowindow = new google.maps.InfoWindow({
          content: map_route.map_settings_destination_address_description
        });
        marker.addListener('click', function() {
          infowindow.open(map, marker);
        });
      }

      const getFormInputElement = (component) => document.getElementById(component + '-input');
      const autocompleteInput = getFormInputElement('location');
      const options = {
        componentRestrictions: { country: 'fr' },
        fields: ['address_components', 'geometry', 'icon', 'name'],
        types: ['address'],
      };
      const autocomplete = new google.maps.places.Autocomplete(autocompleteInput, options);
      let new_place = null,
        new_travel_mode = null;

      autocomplete.addListener('place_changed', function () {
        let client_address_place = autocomplete.getPlace();
        Drupal.behaviors.google_map.client_address_place = client_address_place;
        if (!client_address_place.geometry.location.lat() || !client_address_place.geometry.location.lng()) {
          // User entered the name of a Place that was not suggested and
          // pressed the Enter key, or the Place Details request failed.
          window.alert('No details available for input: \'' + client_address_place.name + '\'');
          return;
        }
      });

      // Geolocation - START.
      // if (map_route.map_settings_map_enable_geoloc) {
      if (true) {
        Drupal.behaviors
          .form_geolocation_client_address
          .initFormGeolocationClientAddress(autocompleteInput);
      }
      // Geolocation - END.

      let map_route_planner = document.getElementById('map_route_planner');
      map_route_planner.addEventListener('click', function () {
        let client_address_place = Drupal.behaviors.google_map.client_address_place;
        if (typeof client_address_place !== 'undefined' && client_address_place !== null) {
          console.log('client_address_place');
          console.log(client_address_place);
          let travelKey = document.querySelector('input[name="travel-mode"]:checked').value,
            travelMode = getTravelMode(travelKey),
            location1, location2,
            marker_infos = {
              'lat': lat,
              'lng': lng,
              'title': map_route.map_settings_destination_address_title
            },
            place_response = {
              'lat': client_address_place.geometry.location.lat(),
              'lng': client_address_place.geometry.location.lng(),
              'title': 'Votre adresse'
            },
            address0 = document.getElementById('address-0'),
            location_input = document.getElementById('location-input'),
            declined_route_plan = true;

          // Verify condition and save the new place state if changed.
          declined_route_plan = declined_route_plan && (
            client_address_place === new_place
          );
          if (client_address_place != new_place) {
            new_place = client_address_place;
          }
          // Verify condition and save the new travelMode state if changed.
          declined_route_plan = declined_route_plan && (
            travelMode === new_travel_mode
          );
          if (travelMode != new_travel_mode) {
            new_travel_mode = travelMode;
          }

          if (map_route.form_enable_element_btn_switch) {
            let is_adresses_switched = Drupal.behaviors.
            form_addresses_switch.isAdressesSwitched();
            declined_route_plan = declined_route_plan && is_adresses_switched;
            // Save the new switch state.
            Drupal.behaviors.form_addresses_switch.saveSwitchState();
          }

          if (declined_route_plan) {
            return;
          }

          Drupal.behaviors.map_route.toggleOverlay('show');

          // Get the two positions.
          if (address0.contains(location_input)) {
            location1 = place_response;
            location2 = marker_infos;
          }
          else {
            location1 = marker_infos;
            location2 = place_response;
          }
          let pointA = new google.maps.LatLng(location1.lat, location1.lng),
            pointB = new google.maps.LatLng(location2.lat, location2.lng);

          // Reset the directions display and the transit and traffic layer.
          if (typeof directionsDisplay !== 'undefined') {

            if( directionsDisplay != null ) {
              directionsDisplay.setMap(null);
              directionsDisplay.setPanel(null);
              directionsDisplay.setRouteIndex(null);
              directionsDisplay = null;

              transitLayer.setMap(null);
              transitLayer = null;

              trafficLayer.setMap(null);
              trafficLayer = null;

              directionsService = null;
            }
          }
          // Reset marker.
          if (marker !== null) {
            marker.setMap(null);
            marker = null;
          }

          // Really necessary this line for set the directionsDisplay ????
          // map = new google.maps.Map($google_map);

          // Instantiate a directions service.
          directionsService = new google.maps.DirectionsService;
          // Create a renderer for directions and bind it to the map.
          directionsDisplay = new google.maps.DirectionsRenderer({
            map: map,
            panel: document.getElementById('directions-panel')
          });

          // Set Layers.
          transitLayer = new google.maps.TransitLayer();
          trafficLayer = new google.maps.TrafficLayer();
          if (travelMode === 'DRIVING') {
            transitLayer.setMap(map);
          }
          if (travelMode === 'TRANSIT') {
            trafficLayer.setMap(map);
          }

          // Get Roads from A to B.
          calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, travelMode, transitLayer, trafficLayer);
        }
      });

      function getTravelMode(travelKey) {
        let travelMode;
        switch (travelKey) {
          case 'walk':
            travelMode = 'WALKING';
            break;

          case 'bike':
            travelMode = 'BICYCLING';
            break;

          case 'transit':
            travelMode = 'TRANSIT';
            break;

          case 'recommended':
            travelMode = 'TRANSIT';
            break;

          case 'two_wheeler':
            travelMode = 'TWO_WHEELER';
            travelMode = 'TRANSIT';
            break;

          case 'car':
          default:
            travelMode = 'DRIVING';
            break;
        }
        return travelMode;
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, travelMode, transitLayer, trafficLayer) {

        directionsService.route({
          origin: pointA,
          destination: pointB,
          avoidTolls: true,
          avoidHighways: false,
          travelMode: travelMode,
          provideRouteAlternatives: true,
          drivingOptions: {
            departureTime: new Date,
            trafficModel: 'pessimistic'
          }
        }, function (response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            for (let road_index = 0, len = response.routes.length; road_index < len; road_index++) {
              new google.maps.DirectionsRenderer({
                directions: response,
                routeIndex: road_index
              });
            }

            let total_number_roads = response.routes.length;

            directionsDisplay.setRouteIndex(total_number_roads);
            directionsDisplay.setDirections(response);

            setTimeout(function(){
              if (map_route.form_enable_element_btn_minimize_restore) {
                Drupal.behaviors.form_minimization.minimize();
              }
              setTimeout(function(){
                Drupal.behaviors.map_route.toggleOverlay('hide');
              }, 375);
            }, 375);

          } else {
            window.alert('Directions request failed due to ' + status);
            Drupal.behaviors.map_route.toggleOverlay('hide');
          }
        });
      }

    }
  };

})(Drupal, drupalSettings);

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc