gpt4 book ai didi

php - 长/纬度查询整个数据库

转载 作者:行者123 更新时间:2023-11-29 18:18:30 26 4
gpt4 key购买 nike

我在 Stack 上发现了这个问题 - Measuring the distance between two coordinates in PHP

这个答案在很多方面似乎对我来说都是完美的,但我遇到了一个问题。我正在设计 CRM,我希望有一个邮政编码半径搜索选项。我的问题是如何针对此查询传递可能有 1,000 条记录并以 HTML 形式显示结果?

最佳答案

所以我通过结合几个来源找到的解决方案是这样的(3959 代表英里,6371 代表公里)。我在下面包含了一个 PHP 文件和一个 HTML 表格,以防其他人解决这个问题。

首先,您可以从此处获取所需的数据:

https://www.freemaptools.com/download-uk-postcode-lat-lng.htm

我建议使用该站点创建一个基本的 MySQL 表并导入数据,但请注意,这将需要一些时间!另外,在我运行查询来删除所有空格之前或之后,使 AA11 1AA 变为 AA111AA,这将使表单验证变得更加简单。

这个简短的演练使用了该链接中的数据和表格构造。

首先,您需要一个如下所示的用户输入表单:

<form action="" method="POST">
<table>
<tr>
<td>Distance:</td>
<td><input type="number" id="distance" name="distance" required></td>
</tr>
<tr>
<td>Miles:<br>Kilometres:</td>
<td><input type="radio" id="unit" name="unit" value="3959" checked><br><input type="radio" id="unit" name="unit" value="6371"></td>
</tr>
<tr>
<td>Postcode:</td>
<td><input type="text" id="postcode" name="postcode" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>

此表单提交到同一页面,因此在您的 .php 文件中,您需要包含此代码以将邮政编码转换为长/纬度值:

<?php include 'credentials.php';

$distance = $_POST['distance'];
$unit = $_POST['unit'];
$postcode = str_replace(' ','',$_POST['postcode']);

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT latitude, longitude FROM postcodelatlng WHERE postcode LIKE '$postcode'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
$latitude = $row['latitude'];
$longitude = $row['longitude'];
}
} else {
echo "Postcode not found";
}
$conn->close();
?>

确保您有一个credentials.php 文件来提供数据库的连接详细信息,以使其正常工作。

然后,在这个 php 脚本的正下方,我们将放置第二个脚本,它将返回特定半径内的所有邮政编码。然后,您可以调整此脚本以满足您的需求。我个人会针对另一个较小的表传递此脚本,以检查 CRM 上的特定半径内是否有任何记录,但目前出于演示目的,只需保持简单即可!

<?php
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT *,
($unit * acos( cos( radians($latitude) ) * cos( radians(latitude) ) * cos( radians(longitude) - radians($longitude)) + sin(radians($latitude)) * sin(radians(latitude)) ))
as distance
FROM postcodelatlng
HAVING distance < $distance";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
echo "" . $row['postcode']. "<br>";
}
} else {
echo "<br>0 results";
}
$conn->close();
?>

主要感谢这篇文章,该文章来自:

Fastest Way to Find Distance Between Two Lat/Long Points

关于php - 长/纬度查询整个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46795262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com