I';m试图在同一个文件(Google Maps API)中将Javascript变量传递给PHP


I'm trying to pass a Javascript variable to PHP within the same file (Google Maps API)

我正在尝试建立一个小站点,跟踪汽车的位置,并将数据存储在数据库中。目前,我已经用一个.php文件设置了所有内容,并嵌入了Javascript——我真的不确定这是否可取,我对网络编程还很陌生。

我需要将大脚本中的"lati"变量发送到PHP脚本(代码底部)。

代码全部工作,它跟踪用户并向数据库提交数据,但它在数据库中填充的字段是空白的:(参见我的代码-

<!DOCTYPE html>
<?php
$username = "ishuttle";
$password = "m7elH07yO2";
$hostname = "localhost"; 
$dbname = "ishuttle_taxi-location";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password, $dbname) 
  or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
 
?>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
	height: 100%;
	margin: 0;
	padding: 100;
}
#map {
	height: 70%;
	width: 100%;
}
</style>
</head>
<body>
<center>
  <h1>DANKCATT DRIVER SIDE APP</h1>
</center>
<div id="map"></div>
<div id="capture"></div>
<script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
	var Lati;
	var Longi;    
	Lati = 3;
	Longi = 3;
 	function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
					  zoom: 15
        });
	var timerID = setInterval(function() {	  
        var infoWindow = new google.maps.InfoWindow({map: map});
	
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
			
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
			var lati = {
              lat: position.coords.latitude
            };
			var longi = {
              lng: position.coords.longitude
            };
			console.log(lati, "Lol");
            infoWindow.setPosition(pos);
            infoWindow.setContent('lati');
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
		
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
    
      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn''t support geolocation.');
      }
		
	  //in a loop (setInterval) get coords and apply them to database
	  
	  }, 10 * 1000); 
	  
	  }
	  //reverse this for the home page - drag the coords out of the db and display them on a loop
	 google.maps.event.addDomListener(window, 'load', getLocation); 
	  
    </script> 
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDONVV6mCAgATiPAanIbdfY55_felLGHHk&callback=initMap">
    </script>
<?php 
 
    
    $lati = $_GET['Lati'];
	$sql = "UPDATE driver_location SET Latitude = '$lati' WHERE ID_No = 1111;";
 echo "$lati";
  if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}
?>
</body>
</html>

您可能需要将php数据库代码分离到另一个文件中,以便从javascript文件到php文件执行ajax发布。

下面是一个使用jquery的ajax文章示例。这是允许您从javascript发布到php页面的javascript:

 $.ajax({
        method: 'POST',
        url: 'likeComment.php',
        data: {'commentId': commentId},
        success: afterLikeComment,
        dataType: 'json'});

Learn Jquery是一个学习Jquery的网站,这里是Jquery网站本身Jquery网站。jQuery是一个Javascript包装器,它使选择dom元素和发布到php等操作变得更加容易。