首页 > 解决方案 > 当我单击带有 Java 脚本功能的按钮时,我收到一条消息,指出该功能未定义

问题描述

JavaScript 中的函数 calcRoute() 未定义以获取方向标记按钮

当我点击获取方向时

在此处输入图像描述

在按钮上,我收到一条消息,指出该功能未定义。先感谢您。

我将我的函数 calcRoute(i) 放在外面,但我收到另一条错误消息,“无法读取未定义的属性 1”,他认为我已经在另一个函数中定义的 location[][] 变量不存在。但我需要这个变量中的信息,但我不能在 calcRoute(i) 中使用它。所以我希望你能在这方面帮助我。

function initMap() {
                // directionService et directionDisplay pour trouver la route
                var directionsService = new google.maps.DirectionsService();
                var directionsDisplay = new google.maps.DirectionsRenderer();
                // Créer l'objet "map" et l'insèrer dans l'élément HTML qui a l'ID "map"
                map = new google.maps.Map(document.getElementById("map"), {
                    // Nous plaçons le centre de la carte avec les coordonnées ci-dessus
                    center: new google.maps.LatLng(lat, lon), 
                    // Nous définissons le zoom par défaut
                    zoom: 14, 
                    // Nous définissons le type de carte (ici carte routière)
                    mapTypeId: google.maps.MapTypeId.ROADMAP, 
                    // Nous activons les options de contrôle de la carte (plan, satellite...)
                    mapTypeControl: true,
                    // Nous désactivons la roulette de souris
                    scrollwheel: false, 
                    mapTypeControlOptions: {
                        // Cette option sert à définir comment les options se placent
                        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR 
                    },
                    // Activation des options de navigation dans la carte (zoom...)
                    navigationControl: true, 
                    navigationControlOptions: {
                        // Comment ces options doivent-elles s'afficher
                        style: google.maps.NavigationControlStyle.ZOOM_PAN 
                    }
                });

                directionsDisplay.setMap(map);


                   <?php


                 $sql = "select count(*) as count from parkings";
            //echo"$sql";
            $res = mysqli_query($cn,$sql);

            if(mysqli_num_rows($res)>0)
            {
                if($ligne = mysqli_fetch_array($res))
                {
                    $nbrParking = $ligne['count'];
                }
            }

                $ip=$_SERVER['REMOTE_ADDR'];
                $geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip='193.52.45.31'"));
                $Usercity = $geo["geoplugin_city"];
                $Userregion = $geo["geoplugin_regionName"];
                $Usercountry = $geo["geoplugin_countryName"];
                $Userlatitude = $geo["geoplugin_latitude"];
                $Userlongitude = $geo["geoplugin_longitude"];

                //echo "City: ".$Usercity."<br>";
                //echo "Region: ".$Userregion."<br>";
                //echo "Country: ".$Usercountry."<br>";
                //echo "Latitude: ".$Userlatitude."</br>";
                //echo "Longitude: ".$Userlongitude."</br>";


                // j'ai mit c'est informations dans une variable Userlocation pour l'utiliser en bas en JavaScript pour calculer la distance entre l'utilisateur et le parking.


                echo"var Userlocation =[$Userlatitude,$Userlongitude] ;";



                $sql = "select * from parkings";
                //echo"$sql";
                $res = mysqli_query($cn,$sql);
                $i=0;   
                if(mysqli_num_rows($res)>0)
                {
                    echo"var location =[";
                    while($ligne = mysqli_fetch_array($res))
                    {

                        $NomParking = $ligne['NomParking'];
                        $Ville = $ligne['Ville'];
                        $Place_Total = $ligne['Place_Total'];
                        $Nbr_voiture = $ligne['Nbr_voiture'];
                        $Longitude = $ligne['Longitude'];
                        $Latitude = $ligne['Latitude'];
                        $idParking = $ligne['Id'];  

                        $place_dispo = $Place_Total - $Nbr_voiture;
                        $TauxRemplissage = ($Nbr_voiture * 100)/$Place_Total;
                        $i++;

                        // mettre la couleure seulon le taux de remplissage
                        if( ($TauxRemplissage>=0) && ($TauxRemplissage<=60))
                        {
                            $couleur ='green';
                        }
                        else if(($TauxRemplissage > 60) && ($TauxRemplissage < 85))
                        {
                            $couleur = 'orange';
                        }
                        elseif(($TauxRemplissage >85) && ($TauxRemplissage<99) && ($place_dispo >1))
                        {
                            $couleur = 'red';
                        }
                        else
                        {
                            $couleur = 'bloque';
                        }


                        if($i == $nbrParking)
                        {
                            echo "['$idParking',$Latitude,$Longitude,'$NomParking',$Nbr_voiture,$place_dispo,$TauxRemplissage,'$couleur']];";
                        }
                        else
                        {
                            echo "['$idParking',$Latitude,$Longitude,'$NomParking',$Nbr_voiture,$place_dispo,$TauxRemplissage,'$couleur'],";
                        }
                    }

                }

                ?>

                function GetUserLocation()
                {
                    if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(position) {
                        var UserLocation = [position.coords.latitude,position.coords.longitude];
                        return UserLocation;
                        });
                    }
                    return UserLocation;
                }
                // ce lien google/mapfiles , c'est pour changer le form du markeur

                var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
                var icons = {
                  parking: {
                    icon: iconBase + 'parking_lot_maps.png'
                  },
                  library: {
                    icon: iconBase + 'library_maps.png'
                  },
                  info: {
                    icon: iconBase + 'info-i_maps.png'
                  }
                };
                const UserLocation = [];
                var x = document.getElementById("demo");
                if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(position) {
                        var pos = new google.maps.LatLng(position.coords.latitude,
                                                       position.coords.longitude);
                        x.innerHTML = "Latitude: " + position.coords.latitude + 
            "<br>Longitude: " + position.coords.longitude;

            //*************************** ON THIS IS MY QUESTION **********************************    
                        console.log("laltitude: "+position.coords.latitude+" et longitude : "+ position.coords.longitude);
                        //UserLocation = [position.coords.latitude,position.coords.longitude];                          
                        //console.log("UserLocation:"+UserLocation[0]+","+UserLocation[1]);    
                        var marker = new google.maps.Marker({
                        position: pos,    
                        map: map,
                        title: 'Here you are',
                        draggable: true
                        });
                    });

                }



              console.log("lenghth:"+UserLocation.length);  
// la fontion getDistanceFromLatLonInKm calcule la distance entre la location de l'utilisateur et la location de chauqe parking.                
        function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
                var R = 6371; // Radius of the earth in km
                var dLat = deg2rad(lat2-lat1);  // deg2rad below
                var dLon = deg2rad(lon2-lon1); 
                var a = 
                Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
                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 deg2rad(deg) {
            return deg * (Math.PI/180)
        }              





 // ici on ajoute notre point sur la carte ou se localise les parkings dans Brest avec les informatoi -->               

        var infowindow = new google.maps.InfoWindow();

        for (var i = 0; i < location.length; i++)
        {


                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(location[i][1], location[i][2]),
                    icon: icons['parking'].icon,
                    map: map,
                    title: location[i][0]
                });



                //fonctiion add listener qui add les form pour chaque marker
                google.maps.event.addListener(marker, 'click', (function (marker, i) {


                    return function () {

                         if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(position) {
                        var UserLocation = [position.coords.latitude,position.coords.longitude];


                        console.log("parkingLoc:"+location[i][1]+" / "+location[i][2]+" User:"+UserLocation[0]+" / "+UserLocation[1]);
                        // la distance entre chaque point et l'utilisateur.
                        var distance = getDistanceFromLatLonInKm(location[i][1],location[i][2],UserLocation[0],UserLocation[1]).toFixed(1);


                        // je cree le form du content que je vais l'afficher quand je clique sur chaque marker

                        var content = '<div class="info-window" >' +
                '<h3>'+location[i][3]+'</h3>' +
                '<div class="info-content" style="border-color:'+location[i][7]+'">' +
                '<p>'+
                '<br> <b> '+location[i][5]+' places Disponibles </b>'+
                        '<br> Distance: '+distance+' km '+    
                '</p>' +
                '<div id="myProgress"  style="width:100%; background-Color:#ddd;">'+
                '<div id="myBar" style="width:'+location[i][6]+'%; height:30px;background-color:'+location[i][7]+'"><b>'+location[i][6].toFixed(2)+'%</b></div>'+
                '</div>'+            
                '</div>' +
                '<div>'+
                '<button style="background-color:blue;padding:0px;color:white;margin-top:5px;" value="i" id="btn_direction" onclick="calcRoute('+i+')"> Get Direction </button>'+ '</div>'+           
                '</div>';

                        infowindow.setContent(content);
                        infowindow.open(map, marker);






                             });
                         }
                    }
                })(marker, i));      

        }// end for



        }// end initMap

              /*
                // Attaches an info window to a marker with the provided message. When the
                // marker is clicked, the info window will open with the secret message.
                function attachSecretMessage(marker, secretMessage) {
                      var infowindow = new google.maps.InfoWindow({
                        content: secretMessage
                      });

                      marker.addListener('click', function() {
                        infowindow.open(marker.get('map'), marker);
                      });
                }
                */

                    function calcRoute(i) {
                        var selectedIndex = document.getElementById('btn_direction').value;
                        var org = new google.maps.LatLng(location[i][1],location[i][2]);
                        var dest = new google.maps.LatLng(location[i][1],location[i][2]);
                        var request = {
                        origin: org,
                        destination: dest,
                        // Note that Javascript allows us to access the constant
                        // using square brackets and a string value as its
                        // "property."
                        travelMode: google.maps.TravelMode.DRIVING
                        };
                      directionsService.route(request, function(response, status) {
                            if (status === google.maps.DirectionsStatus.OK) {
                              directionsDisplay.setDirections(response);
                            }else {
                                console.log('Directions request failed due to ' + status);
                                }
                      });
                }//end function calcRoute()  



            window.onload = function(){
                // Fonction d'initialisation qui s'exécute lorsque le DOM est chargé

                initMap(); 

            };


        </script>

标签: javascriptphp

解决方案


推荐阅读