【发布时间】:2019-07-09 21:42:06
【问题描述】:
对于我的 Web 应用程序,我正在尝试将 javascript (googleMap.js) 中的纬度和经度变量发布到外部 php 文件 (closestLocations.php)。我正在使用 AJAX 发布方法来发布两个变量,但是我仍然发现这些变量是未定义的。
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>';
【问题讨论】:
-
检查这个类似的线程:- stackoverflow.com/questions/44607232/…
-
您在最近的位置尝试访问发布的变量?
-
对不起,我以为我已经包含了这个,上面的函数 parseToXML 我有 $lat = $_POST['lat']; $lng = $_POST['lng'];
标签: javascript php jquery ajax google-geolocation