1

I have a database with 3000~ locations stored as coordinates. I want to only pick out a certain amount of locations within a radius of x km.

Like this:

Map as an example.

Currently I am generating a XML file with PHP to grab the entries from the database, there should be a way to only pick out the lat/lon that I need withing a certain radius of x lat/x lon. Here's the code:

<?php
require_once("db.php");

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}


// Select all the rows in the markers table
$query = "SELECT * FROM addresses";
$result = mysqli_query($conn, $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 'id="' . $row['id'] . '" ';
  echo 'name="' . $row['id'] . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="House" ';
  echo '/>';
  $ind = $ind + 1;
}

// End XML file
echo '</markers>';

?>
m0nsterr
  • 131
  • 1
  • 6
  • 1
    You may find an answer here: https://stackoverflow.com/questions/7783684/select-coordinates-which-fall-within-a-radius-of-a-central-point – Onki Hara Jun 01 '22 at 18:36
  • @OnkiHara Amazing! I will definitly take a closer look at that! Thanks! :) – m0nsterr Jun 01 '22 at 18:51

1 Answers1

0

Here's the solution I went with.

By changing this:

$query = "SELECT * FROM addresses";

To:

$lat = latitude of radius center
$lon = longtitude of radius center
$km_radius = Radius in kilometers

$query = "SELECT * FROM addresses WHERE 1 = 1 AND 2 * 3961 * asin(sqrt(power((sin(radians(($lat - cast(lat as decimal(10,8))) / 2))) , 2) + cast(cos(radians(cast(lat as decimal(18,8)))) * cos(radians($lat)) + power((sin(radians(($lon - cast(lng as decimal(18,8))) / 2))) , 2) as decimal(18,10) ))) <= ($km_radius * 0.62137)";

m0nsterr
  • 131
  • 1
  • 6