问题描述
当用户单击此页面时,我希望将其所在位置的天气上传到MysqL数据库。我不得不使用PHP将其上传到数据库,这意味着我不得不对经度和纬度进行硬编码。
但是,我有一个javascript文件,可以提取用户的确切位置。我想知道是否可以将其合并到我的PHP代码中以获取用户的确切位置?
<script>
// Check if the user's browser suports location and then get user's current location
if('geolocation' in navigator){
console.log('geolocation is available');
navigator.geolocation.getCurrentPosition(position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
document.getElementById('latitude').textContent = lat;
document.getElementById('longitude').textContent = lon;
//console.log(position);
});
}else{
console.log('geolocation is not available');
}
</script>
<?PHP
include("connect.PHP");
session_start();
$userid = $_SESSION['userid'];
$key = "";
$lat="54.5973";
$lon="-5.9301";
$api = "http://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&appid=".$key;
$response = file_get_contents($api);
$data = json_decode($response,true);
print_r($data);
$temp = $data['main']['temp']-273; // convert to Celsius
$desc = $data['weather'][0]['description'];
$icon = $data['weather'][0]['icon'];
$city = $data['name'];
echo "\n\n"; // clear after print_r
echo "Temperature: ".$temp."\n";
echo "Description: ".$desc."\n";
echo "Icon : ".$icon."\n";
echo "City : ".$city."\n";
$sql = "INSERT INTO weathertype (userid,city,temperature,icon,description) VALUES($userid,'$city',$temp,'$icon','$desc')";
$result = $conn->query($sql);
echo $sql;
$result= "SELECT * from weathertype where userid=$userid";
if($result>0){
$update = "UPDATE weathertype SET city=$city,temperature=$temp,icon=$icon,description=$desc WHERE userid=$userid";
}else{
$sql = "INSERT INTO weathertype (userid,'$desc')";
}
?>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)