无法通过requirejs加载我的所有功能

时间:2018-03-19 19:42:35

标签: javascript jquery requirejs

我必须通过requirejs包含一些js函数,这些函数需要google api,所以:

  1. 我在<head>中添加了google api链接(它放在最后一个)。
  2. 在js文件中包含js函数。
  3. 我在我的phtml中调用这些函数。
  4. 错误:

      
        
    • 未捕获的异常:InvalidValueError:buildMap不是函数

    •   
    • TypeError:标记未定义

    •   

    文件:

    应用/代码/供应商/模块/视图/前端/布局/ module_index_index.xml

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="1column">
        <body>
            <referenceContainer name="head.additional">
                <block class="Vendor\Module\Block\block" name="googlemaps.api" template="Vendor_Module::googlemap-script.phtml" />
            </referenceContainer>
        </body>
    </page>
    

    使用GoogleMap-script.phtml

    <script src="https://maps.googleapis.com/maps/api/js?key=123456&libraries=places&callback=buildMap" async defer></script>
    

    应用/代码/供应商/模块/视图/前端/ requirejs-config.js

    var config = {
        map: {
            '*': {
                module: 'Vendor_module/js/go',
            }
        }
    };
    

    应用/代码/供应商/模块/视图/前端/网络/ JS / go.js

    define(['jquery', 'domReady!'], function($, doc) {
        'use strict';
    
        function setZoom(map, markers)
        {
    
            var boundbox = new google.maps.LatLngBounds();
                for ( var i = 0; i < markers.length; i++ )
                {
                  boundbox.extend(new google.maps.LatLng(markers[i]['latitude'], markers[i]['longitude']));
                }
                map.setCenter(boundbox.getCenter());
                map.fitBounds(boundbox);
    
        }
    
        function buildMap()
        {
            var options = {
                mapTypeId: google.maps.MapTypeId.ROADMAP //SATELLITE,ROADMAP,HYBRID
                };
                    map = new google.maps.Map(document.getElementById("map"), options);
                    //var marker = new google.maps.Marker({map: map, position:latlng});
                    $.each(jsStoreTab, function(index,valeur)
                    {//each paire de données
                        setTimeout(function() {
                            latlng = new google.maps.LatLng(parseFloat(valeur['latitude']),parseFloat(valeur['longitude']));
                            cm_createMarker(latlng, 'html', index+1,valeur);
                        }, index * 200);
    
    
                            })
    
    
                            if(jsStoreTab.length>1) setZoom(map,jsStoreTab);
                            else
                            {
                                var centreCarte = new google.maps.LatLng(parseFloat(jsStoreTab[0]['latitude']),parseFloat(jsStoreTab[0]['longitude']));
                                map.setZoom(13);
                                map.setCenter(centreCarte);
    
                            }
                            directionsService = new google.maps.DirectionsService();
                            directionsDisplay = new google.maps.DirectionsRenderer();
                            initAutocomplete();
                            $.each(filtersTab, function(idxFilterGroup,filterGroup){
                                $('#filters').append('<fieldset class="'+idxFilterGroup+'"><legend>'+filterGroup.name+'<a title="Informations sur les '+filterGroup.name+'" href="'+filterGroup.url+'" target="_blank"></a></legend></fieldset>');
    
                                $.each(filterGroup.datas, function(idxFilter,filter){
                                    $('#filters fieldset.'+idxFilterGroup).append('<input filter_group="'+idxFilterGroup+'" type="checkbox" id="'+filter.replace(/ /g ,'_')+'" onclick="markerFilter()" value="'+filter+'"><label for="'+filter.replace(/ /g ,'_')+'">'+filter+'</label>');
                                });
    
                            });
        }
    
        function markerFilter()
        {
    
            if($('#filters fieldset input:checked').length==0)
            {
                $.each(allMarkers,function(idx,marker){marker.setVisible(true);});
                return true;
            }
            $.each(allMarkers,function(idx,marker){
                marker.setVisible(false);
                $.each($('#filters fieldset input'),function(idxInp,inp){
                    if($(inp).prop("checked"))
                    {
                        $.each($('#filters fieldset input'),function(idxInp,inp){
                            if($(inp).prop("checked"))
                            {
            console.log('CHECKED',$(inp).attr('id'),$(inp).attr('filter_group'), marker.datas[$(inp).attr('filter_group')] );
                                if(typeof marker.datas[$(inp).attr('filter_group')]!== 'undefined' && marker.datas[$(inp).attr('filter_group')].indexOf($(inp).val())!=-1 ) marker.setVisible(true);
                            }
                        });
                    }
                });
            });
        }
    
        function attachInfoWindow(marker, num)
        {
              marker.addListener('click', function() {
                if (infowindow) { infowindow.close();}
                infowindow= new google.maps.InfoWindow({
                  content: $('#listeStations li.store[data-markerid='+num+']').html()
                });
                infowindow.open(marker.get('map'), marker);
                $('#list li.store').removeClass('list-focus');
                $('#list li.store[data-markerid='+num+']').addClass('list-focus');
              });
    
        }
    
        function initAutocomplete()
        {
            var options = {
                types: ['geocode'],
                componentRestrictions: {country: "fr"}
            };
            autocomplete = new google.maps.places.Autocomplete(
            (document.getElementById('select-ville')),options);
            autocomplete.addListener('place_changed', fillInAddress);
        }
    
        function fillInAddress()
        {
            // Get the place details from the autocomplete object.
                var place = autocomplete.getPlace();
                maPosition.latitude=place.geometry.location.lat();
                maPosition.longitude=place.geometry.location.lng();
    
                var maPos = new google.maps.LatLng(place.geometry.location.lat(),place.geometry.location.lng());
                if(allMarkers.length>jsStoreTab.length) allMarkers[allMarkers.length-1].setMap(null);//suppression de la dernière position
                var marker = new google.maps.Marker({
                          position: maPos,
                          map: map,
                          title: "Vous êtes ici",
                          animation: google.maps.Animation.DROP
                      });
                allMarkers.push(marker);
                var minDist=999999999;
                var bestPos=0;
                $.each(jsStoreTab, function(index,valeur)
                {
                    var dist=calculdist(maPosition,valeur);
                    if(dist<minDist)
                    {
                        minDist=dist;
                        bestPos=valeur;
                    }
                })
                var markerBounds=[bestPos,{'latitude':maPosition.latitude,'longitude':maPosition.longitude,'name':'Vous êtes ici'}];
    
                setZoom(map, markerBounds);
                routeInitialize();
                calcRoute(maPosition,bestPos);
    
                //calculdist(parseFloat($('#autocompGoogleForm #latitude').val()),parseFloat($('#autocompGoogleForm #longitude').val()));
                return false;
        }
    
            // Bias the autocomplete object to the user's geographical location,
        function geolocate()
        {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                var geolocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                var circle = new google.maps.Circle({
                    center: geolocation,
                    radius: position.coords.accuracy
                });
                autocomplete.setBounds(circle.getBounds());
                });
            }
        }
        function deg2rad(deg)
        {
            return deg * (Math.PI/180)
        }
    
        function calculdist(pos1,pos2)
        {
            var R = 6371; // Radius of the earth in km
            var dLat = deg2rad(pos1.latitude-pos2.latitude);  // deg2rad below
            var dLon = deg2rad(pos1.longitude-pos2.longitude );
            var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(pos2.latitude)) * Math.cos(deg2rad(pos1.latitude)) * Math.sin(dLon/2) * Math.sin(dLon/2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            var d = R * c; // Distance in km
            return d;
         }
    
        function routeInitialize()
        {
            directionsDisplay.setMap(null);
            directionsDisplay.setMap(map);
        }
    
        function calcRoute(start,end)
        {
          var request = {
            origin: new google.maps.LatLng(start.latitude, start.longitude),
            destination: new google.maps.LatLng(end.latitude, end.longitude),
            travelMode: 'DRIVING',
            drivingOptions: {
                departureTime: new Date(Date.now() ),  // + Nfor the time N milliseconds from now.
                trafficModel: 'optimistic'
            },
            unitSystem: google.maps.UnitSystem.METRIC // en kms
    
          };
          directionsService.route(request, function(result, status) {
            if (status == 'OK') {
                directionsDisplay.setDirections(result);
                //https://developers.google.com/maps/documentation/javascript/directions#DirectionsResults
                var distance = 0;
                var delay = 0;
                var legs = result.routes[0].legs;
                for(var i=0; i<legs.length; ++i) {
                    distance += legs[i].distance.value;
                    delay += legs[i].duration.value;
                }
    
    
                var days= parseInt(delay / (3600*24));
                var restDays=delay%(3600*24);
                var hours=parseInt(restDays/3600);
                var restHours=restDays%3600;
                var min=parseInt(restHours/60);
    
                var delayPrint='';
                if(days>0) delayPrint+=days+' jours ';
                if(hours>0) delayPrint+=hours+' h ';
                if(min>0) delayPrint+=min+' min';
    
    
                $('#distance').text(Math.round(distance/1000)+' kms');
                $('#duree').text(delayPrint);
    
            }
          });
    
        }
    
        function stOver(num,id)
        {
            //console.log('stOver',num,id);
            //https://mapicons.mapsmarker.com/numbers-letters/numbers/?style=iphone&custom_color=23a605
                allMarkers[num].setIcon("https://www.oselia-beaute.com/media/storelocator/images/markers/black/number_"+id+".png");
        }
    
        function stOut(num,id)
        {
    
            //https://mapicons.mapsmarker.com/numbers-letters/numbers/?style=iphone&custom_color=23a605
                allMarkers[num].setIcon("https://www.oselia-beaute.com/media/storelocator/images/markers/yellow/number_"+id+".png");
    
        }
    
        function cm_createMarker(point, html, rank,tab)
        {
            //https://mapicons.mapsmarker.com/numbers-letters/numbers/?style=iphone&custom_color=23a605
            //console.log("https://www.oselia-beaute.com/media/storelocator/images/markers/green/number_';?>"+rank+".png");
                  var image = new google.maps.MarkerImage("https://www.oselia-beaute.com/media/storelocator/images/markers/yellow/number_"+rank+".png",
                              new google.maps.Size(32, 37),
                              new google.maps.Point(0, 0),
                              new google.maps.Point(10, 34));
    
    
    
                  var marker = new google.maps.Marker({
                      position: point,
                      map: map,
                      icon: image,
                      title: tab.name,
                      animation: google.maps.Animation.DROP,
                      datas : tab
                  });
                  attachInfoWindow(marker,parseInt(rank));
                  allMarkers.push(marker);
        }
        function logit() {
            console.log('hi');
        }
    
        //I return all the functions for the phtml
        return {
            setZoom         : setZoom,
            buildMap        : buildMap,
            markerFilter    : markerFilter,
            attachInfoWindow : attachInfoWindow,
            initAutocomplete : initAutocomplete,
            fillInAddress   : fillInAddress,
            geolocate       : geolocate,
            deg2rad         : deg2rad,
            calculdist      : calculdist,
            routeInitialize : routeInitialize,
            calcRoute       : calcRoute,
            stOver          : stOver,
            stOut           : stOut,
            cm_createMarker : cm_createMarker,
            logit : logit
        }
    
    });
    

    file.phtml

    <script type="text/javascript">
    require(['jquery', 'domReady!', 'module'], function($, doc, module) {
        'use strict';
        module.setZoom();
        module.buildMap();
        module.markerFilter();
        module.attachInfoWindow();
        module.initAutocomplete();
        module.fillInAddress();
        module.geolocate();
        module.deg2rad();
        module.calculdist();
        module.routeInitialize();
        module.calcRoute();
        module.stOver();
        module.stOut();
        module.cm_createMarker();
        module.logit();
    });
    

    信息:我认为他无法加载google api,(我在页面模块的源代码中看到它)这是所有第一个函数打破我的上一个测试函数{ {1}},就像这样,我无法看到module.logit();的console.log,但是如果我将它放在phtml的所有功能之前,我的logit()消息&#39; hi&# 39;出现。

0 个答案:

没有答案