【问题标题】:How to pass php variable values into javascript var variables without onClick function?如何在没有 onClick 函数的情况下将 php 变量值传递给 javascript var 变量?
【发布时间】:2017-11-28 10:16:08
【问题描述】:

我在 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>

【问题讨论】:

  • 可以将其作为js变量回显:echo "";
  • 你的项目中的php和js代码是在同一个文件吗?还是在单独的文件中?

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


【解决方案1】:

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

<?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);
      }
    });

【讨论】:

    【解决方案2】:

    您可以像这样将数据回显到 JS 变量中...

    var point1 = {lat: <?php echo $lat1 ?>, lng: <?php echo $lon1 ?>}; 
    var point2 = {lat: <?php echo $lat2 ?>, lng: <?php echo $lon2 ?>};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-08
      • 2015-07-10
      • 2018-04-19
      相关资源
      最近更新 更多