HTML5地理位置,在页面加载时将lat / long传递给PHP变量

时间:2017-06-23 17:07:16

标签: php html5

在这段代码中,我需要将lat和long指定为php变量..请帮助我

<!DOCTYPE html><html><body><p id="demo"></p><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)
    {
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;  
    }
    getLocation()
    </script>

1 个答案:

答案 0 :(得分:0)

这假设您有一个包含长列和纬度列的“用户”表。

<强> somescript.php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$stmt = $conn->prepare("INSERT INTO users (long, lat) VALUES (:long, :lat)");
$stmt->bindParam(':long', $long);
$stmt->bindParam(':lat', $lat);
$long = $_REQUEST['long'];
$lat = $_REQUEST['lat'];
$stmt->execute();

您的javascript:

function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position)
{
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            alert("Success");
        }
    };
    xmlhttp.open("GET", "somescript.php?lat=" + lat + "&long=" + long, true);
    xmlhttp.send();
}
getLocation();

类似地,你会对UPDATE语句做同样的事情。