对于我的Web应用程序,我试图将纬度和经度变量从javascript(googleMap.js)发布到外部php文件(closestLocations.php)。我正在使用AJAX post方法来发布两个变量,但是仍然无法确定这些变量。
closestLocations.php文件正在生成一个xml文件,其中包含与特定位置相关的位置列表(目前,经度和纬度已进行了硬编码,但我想将其更改为这些变量)。
任何帮助将不胜感激
googleMap.js
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
myPosition = {lat: latitude, lng: longitude};
$.ajax({
type: "POST",
data: {lat:latitude,lng:longitude},
url: "php/closestLocations.php",
success: function(data){
console.log(latitude);
}
});
//personalise infowindow
infoWindow.setPosition(myPosition);
infoWindow.setContent('You Are Here!');
infoWindow.open(map);
map.setCenter(myPosition);
//display marker on map where user is located
var marker = new google.maps.Marker({
map: map,
position: myPosition,
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
closestLocations.php
require_once("closestLocations.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
$connection=mysqli_connect ('localhost', $username, $password);
if (!$connection) {
die('Not connected : ' . mysqli_error());
}
// Set the active MySQL database
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
die ('Can\'t use db : ' . mysqli_error());
}
$query = "SELECT locationName, address, town, postcode, telephone, ( 3959 * acos ( cos ( radians(50.6346) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-6.6169) ) + sin ( radians(50.6346) ) * sin( radians( lat ) ) ) ) AS distance FROM defibrillators HAVING distance < 5 ORDER BY distance LIMIT 0 , 10 ";
$result=mysqli_query($connection, $query);
if(!$result){
die('Invalid query: ' . mysqli_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo "<?xml version='1.0' ?>";
echo '<markers>';
$ind=0;
// Iterate through the rows, printing XML nodes for each
while ($row = @mysqli_fetch_assoc($result)){
// Add to XML document node
echo '<marker ';
echo 'name="' . parseToXML($row['locationName']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'town="' . parseToXML($row['town']) . '" ';
echo 'postcode="' . parseToXML($row['postcode']) . '" ';
echo 'telephone="' . parseToXML($row['telephone']) . '" ';
echo '/>';
$ind = $ind + 1;
}
// End XML file
echo '</markers>';
答案 0 :(得分:0)
您的JS ajax调用正在通过POST方法请求PHP文件,因此您在数据中发布的变量将在$ _POST超全局变量的PHP脚本中可用。
var_dump($_POST); // array(2) { ["lat"]=> string(1) "1" ["lng"]=> string(1) "2" }
因此可以通过$ _POST ['lat']访问纬度;和经度通过$ _POST ['lng']