adding PHP variables into Javascript functions using Google Directions API

348 Views Asked by At

I am fairly new using google APIs. I am creating an application where I need to use addresses saved in a database t0 display a route to an event. I have found a template allowing me to manually change the Javascript variables in the google maps API however when I try to use a PHP variable in the function it won't load the map. I haven't connected it to my database yet, I am just trying to get it working with PHP variables

Just wondered if anyone could point me in the right direction and help me out.

  <head>
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
   <title>Google Maps API v3 Directions Example</title>
   <script type="text/javascript"
           src="https://maps.googleapis.com/maps/api/js?
key=MYKEYHERE&callback=initMap"></script></head>

<?php 
$start = "Leeds";
$end = "Nottingham";
?>

<body>


     <div id="map"></div>

     <div id="right-panel"></div>


   <script type="text/javascript">

     var directionsService = new google.maps.DirectionsService();
     var directionsDisplay = new google.maps.DirectionsRenderer();

     var map = new google.maps.Map(document.getElementById('map'), {
       zoom:7,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     });

     directionsDisplay.setMap(map);
     directionsDisplay.setPanel(document.getElementById('right-panel'));


     var request = {
       origin: <?php echo $start; ?>,
       destination: <?php echo $end; ?>,
       travelMode: google.maps.DirectionsTravelMode.DRIVING
     };

     directionsService.route(request, function(response, status) {
       if (status == google.maps.DirectionsStatus.OK) {
         directionsDisplay.setDirections(response);
       }
     });
   </script>
</body>
</html>
1

There are 1 best solutions below

0
On

I have reviewed your code and lt looks like you are passing the origin and Destination values as "STRING CONTAING THE PLACE NAME" , Where as in google Maps API , it shall receive the coordinates of a place , the lat and long for a place in this way as stated in the google map api https://developers.google.com/maps/documentation/javascript/examples/directions-travel-modes :

origin: {lat: 37.77, lng: -122.447},  // Haight.
destination: {lat: 37.768, lng: -122.511},  // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]

So you shall replace your following code :

 var request = {
       origin: <?php echo $start; ?>,
       destination: <?php echo $end; ?>,
       travelMode: google.maps.DirectionsTravelMode.DRIVING
     };

With a code similar to the one I have just post above . Hope this will help you .