title: when i click a button with Java script function i receive a message that the function isn't defined
body: <p>function calcRoute() in JavaScript undefined to get direction marker button</p>
  
  <p>when i click on get direction</p>
  
  <p><a href="https://i.stack.imgur.com/BghwU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BghwU.png" alt="enter image description here"></a></p>
  
  <p>on button i receive a message that the function is not defined. Thank you in advance.</p>
  
  <p>i putted my function calcRoute(i) outside but i receive another error message that "connot read proprety 1 of undifined" he condider by this message that the location[][] variable that i have already defined in another function doesn't excist. but i neeed the information  in this variable but i can't use it in calcRoute(i). So i hope that you can help me in this.</p>
  
  <pre><code>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);
  
  
                     &lt;?php
  
  
                   $sql = "select count(*) as count from parkings";
              //echo"$sql";
              $res = mysqli_query($cn,$sql);
  
              if(mysqli_num_rows($res)&gt;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."&lt;br&gt;";
                  //echo "Region: ".$Userregion."&lt;br&gt;";
                  //echo "Country: ".$Usercountry."&lt;br&gt;";
                  //echo "Latitude: ".$Userlatitude."&lt;/br&gt;";
                  //echo "Longitude: ".$Userlongitude."&lt;/br&gt;";
  
  
                  // 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)&gt;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&gt;=0) &amp;&amp; ($TauxRemplissage&lt;=60))
                          {
                              $couleur ='green';
                          }
                          else if(($TauxRemplissage &gt; 60) &amp;&amp; ($TauxRemplissage &lt; 85))
                          {
                              $couleur = 'orange';
                          }
                          elseif(($TauxRemplissage &gt;85) &amp;&amp; ($TauxRemplissage&lt;99) &amp;&amp; ($place_dispo &gt;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'],";
                          }
                      }
  
                  }
  
                  ?&gt;
  
                  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 + 
              "&lt;br&gt;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 --&gt;               
  
          var infowindow = new google.maps.InfoWindow();
  
          for (var i = 0; i &lt; 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 = '&lt;div class="info-window" &gt;' +
                  '&lt;h3&gt;'+location[i][3]+'&lt;/h3&gt;' +
                  '&lt;div class="info-content" style="border-color:'+location[i][7]+'"&gt;' +
                  '&lt;p&gt;'+
                  '&lt;br&gt; &lt;b&gt; '+location[i][5]+' places Disponibles &lt;/b&gt;'+
                          '&lt;br&gt; Distance: '+distance+' km '+    
                  '&lt;/p&gt;' +
                  '&lt;div id="myProgress"  style="width:100%; background-Color:#ddd;"&gt;'+
                  '&lt;div id="myBar" style="width:'+location[i][6]+'%; height:30px;background-color:'+location[i][7]+'"&gt;&lt;b&gt;'+location[i][6].toFixed(2)+'%&lt;/b&gt;&lt;/div&gt;'+
                  '&lt;/div&gt;'+            
                  '&lt;/div&gt;' +
                  '&lt;div&gt;'+
                  '&lt;button style="background-color:blue;padding:0px;color:white;margin-top:5px;" value="i" id="btn_direction" onclick="calcRoute('+i+')"&gt; Get Direction &lt;/button&gt;'+ '&lt;/div&gt;'+           
                  '&lt;/div&gt;';
  
                          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(); 
  
              };
  
  
          &lt;/script&gt;
  </code></pre>