GeoLocation跟踪并插入mysqlDatabse

时间:2020-06-03 12:20:36

标签: javascript php geolocation

我想跟踪用户位置并保存到数据库中
我在加载页面时使用地理位置脚本将用户位置数据跟踪到mysql数据库中。但是,地理位置数据未插入数据库。这是代码

<?php
require('config.php');
$data1=$_POST['location'];
mysqli_query($con,"insert into table(raw) values('$data1')");
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body onload="getLocation()">
<form method="post" action="">
<input name="location" id="demo" type="hidden" /></form>
<script>
var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}
function showPosition(position) {
  var latlon = position.coords.latitude + "," + position.coords.longitude;

  var url = "https://www.google.com/maps/@"+latlon;
 x.innerHTML = url;
}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的操作方式有误。您会看到代码执行顺序,主体将在表单之前加载,并且<form> </form>不会将任何内容回发到php脚本中,因为仅字段(即隐藏)不包含任何值。 为此,您需要在代码中执行以下操作:

<pre><form><input type="hidden" id="demo" name="location" value="" />
<script type="text/javascript">
 var elem = document.getElementById("demo");
 elem.value = navigator.geolocation.getCurrentPosition(showPosition);
</script></form>