I am using the code provided by Google showing their Google Maps Directions API. I have manually changed the origin and destination values and it works perfectly. However when trying to replace the origin and destination values with PHP variables the map won't load.
Here's my code, any advice would be greatly appreciated.
<body>
<?php
$start = "Leeds";
$end = "Nottingham";
?>
<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>
I believe you're missing quotes around the PHP. Try this. When you use echo in PHP,
$Example = "hey";
The PHP will only echo whats inside the quotes. So in your JavaScript you have to add them manually or your result is
origin: Start,
destination: End
It needs to be
origin: 'Start',
destination: 'End'
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.