gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:16:50 24 4
gpt4 key购买 nike

我在 php 变量中有一个坐标(latlng)。我需要将这些变量传递给 javascript google map api 请求。我想在 javascript 中将 $lat1 和 $lon1 传递给 point1 而无需 onClick 函数。我怎样才能实现这个目标?

    <?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>

最佳答案

只需使用 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);
}
});

关于javascript - 如何在没有 onClick 函数的情况下将 php 变量值传递给 javascript var 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com