如何在没有onClick函数的情况下将php变量值传递给javascript var变量?

时间:2017-11-28 10:16:08

标签: javascript php google-maps-api-3

我在php变量中有一个坐标(latlng)。我需要将这些变量传递给javascript google maps api请求。我想在没有onClick函数的情况下将$ lat1和$ lon1传递给javascript中的point1。我怎样才能做到这一点?

    <?php
    $lat1 = 6.893732;
    $lon1 = 79.857516;
    $lat2 = 6.856007;
    $lon2 = 79.865284;
    ?>


    <html>
       <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
        async defer></script>
        <script>
            var point1 = {lat: 41.85, lng: -87.65}; //Send $point1 value here
            var point2 = {lat: 39.79, lng: -86.14}; //Send $point2 value here

            // Set destination, origin and travel mode.
          var request = {
          destination: point1,
          origin: point2,
          travelMode: 'DRIVING'
        };

        // Pass the directions request to the directions service.
        var directionsService = new google.maps.DirectionsService();
        directionsService.route(request, function(response, status) {
          if (status == 'OK') {
            // Display the route on the map.
            directionsDisplay.setDirections(response);
          }
        });

</script>

1 个答案:

答案 0 :(得分:4)

只需在您的javascript代码中使用php打印它,如下所示:

<?php
$lat1 = 6.893732;
$lon1 = 79.857516;
$lat2 = 6.856007;
$lon2 = 79.865284;
?>


<html>
   <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>
    <script>
        var point1 = {lat: <?php echo $lat1 ?>, lng: <?php echo $lon1 ?>}; //Send $point1 value here
        var point2 = {lat: <?php echo $lat2 ?>, lng: <?php echo $lon2 ?>}; //Send $point2 value here

        // Set destination, origin and travel mode.
      var request = {
      destination: point1,
      origin: point2,
      travelMode: 'DRIVING'
    };

    // Pass the directions request to the directions service.
    var directionsService = new google.maps.DirectionsService();
    directionsService.route(request, function(response, status) {
      if (status == 'OK') {
        // Display the route on the map.
        directionsDisplay.setDirections(response);
      }
    });