Radius Based Location Search with PHP and MySQL

The search feature allows the user to find the specific data from a large number of records quickly. Generally, when a search request is submitted, the filtered data is fetched from the database. If you have a large number of records, the search feature is very useful to make the data list user-friendly.

Search based on the latitude and longitude is used to find the records within a certain distance. Mostly, the location-based search is used for the property/store/place list. It allows finding the places within a defined radius. In this tutorial, we will show you how to integrate radius based location search with latitude & longitude using PHP and MySQL.

In the example script, we will implement the following functionality to demonstrate geographic searches within a certain radius with PHP and MySQL.

  • Fetch the places from the database and listed on the webpage.
  • Calculate circle distance based on latitude and longitude.
  • Search places based on the radius distance.
  • List filtered data within a defined radius.

Create Database Table

For this example, we will create a places table with some basic fields in the MySQL database. The places table holds the records which will be searched.

CREATE TABLE `places` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `address` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
 `latitude` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `longitude` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect the database using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

<?php 
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}

Search Records Based on Radius Distance

Search Query:
Initially, all the records are fetched from the database with PHP and MySQL.

  • If radius based search request is submitted,
    • Based on the latitude and longitude of the searched location, the distance of the places is calculated in the MySQL SELECT query.
    • The records are fetched in order by the distance.
<?php 
// Include database configuration file
require_once 'dbConfig.php';

// If search form is submitted
if(isset($_POST['searchSubmit'])){
    if(!empty(
$_POST['location'])){
        
$location $_POST['location'];
    }
    
    if(!empty(
$_POST['loc_latitude'])){
        
$latitude $_POST['loc_latitude'];
    }
    
    if(!empty(
$_POST['loc_longitude'])){
        
$longitude $_POST['loc_longitude'];
    }
    
    if(!empty(
$_POST['distance_km'])){
        
$distance_km $_POST['distance_km'];
    }
}

// Calculate distance and filter records by radius
$sql_distance $having '';
if(!empty(
$distance_km) && !empty($latitude) && !empty($longitude)){
    
$radius_km $distance_km;
    
$sql_distance " ,(((acos(sin((".$latitude."*pi()/180)) * sin((`p`.`latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`p`.`latitude`*pi()/180)) * cos(((".$longitude."-`p`.`longitude`)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance ";
    
    
$having " HAVING (distance <= $radius_km) ";
    
    
$order_by ' distance ASC ';
}else{
    
$order_by ' p.id DESC ';
}

// Fetch places from the database
$sql "SELECT p.*".$sql_distance." FROM places p $having ORDER BY $order_by";
$query $db->query($sql);
?>

Search Form:
An HTML form is provided to input the certain location and distance within the search for.

  • For location input, we will use the autocomplete field to select a certain place.
  • A dropdown will be placed to select radius distance.
<form method="post" action="">
    <input type="text" name="location" id="location" value="<?php echo !empty($location)?$location:''?>" placeholder="Type location...">
    <input type="hidden" name="loc_latitude" id="latitude" value="<?php echo !empty($latitude)?$latitude:''?>">
    <input type="hidden" name="loc_longitude" id="longitude" value="<?php echo !empty($longitude)?$longitude:''?>">
	
    <select name="distance_km">
        <option value="">Distance</option>
        <option value="5" <?php echo (!empty($distance_km) && $distance_km == '5')?'selected':''?>>+5 KM</option>
        <option value="10" <?php echo (!empty($distance_km) && $distance_km == '10')?'selected':''?>>+10 KM</option>
        <option value="15" <?php echo (!empty($distance_km) && $distance_km == '15')?'selected':''?>>+15 KM</option>
        <option value="20" <?php echo (!empty($distance_km) && $distance_km == '20')?'selected':''?>>+20 KM</option>
    </select>
    <input type="submit" name="searchSubmit" value="Search" />
</form>

Google Maps JavaScript API:
The following JavaScript is required to add autocomplete location features to the input field using Google Maps JavaScript API with Places Library.

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<!-- Google Maps JavaScript library -->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=Your_API_Key"></script>

<script>
var searchInput = 'location';

$(document).ready(function () {
    var autocomplete;
    autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
        types: ['geocode'],
    });
	
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var near_place = autocomplete.getPlace();
        document.getElementById('latitude').value = near_place.geometry.location.lat();
        document.getElementById('longitude').value = near_place.geometry.location.lng();
    });
});

$(document).on('change', '#'+searchInput, function () {
    document.getElementById('latitude').value = '';
    document.getElementById('longitude').value = '';
});
</script>

Note That: You need to specify your Google Maps API key in the key parameter of Google Maps JavaScript API.

Autocomplete Address Field using Google Maps JavaScript API with Places Library

Data List Based on the Radius

Based on the selected distance, the places located within this radius will be listed on the webpage.

<?php 
if($query->num_rows 0){
    while(
$row $query->fetch_assoc()){
?>
    <div class="pbox">
        <h4><?php echo $row['title']; ?></h4>
        <p><?php echo $row['address']; ?></p>
        <?php if(!empty($row['distance'])){ ?>
        <p>Distance: <?php echo round($row['distance'], 2); ?> KM<p>
        <?php ?>
    </div>
<?php
    
}
}else{
    echo 
'<h5>Place(s) not found...</h5>';
}
?>

Ajax Pagination with Search and Filter in PHP

Conclusion

Radius based search is very useful for the property list where records need to be searched within a certain distance. In this example code, we have used places to search by distance. But, this script can be used for any searches where you want to filter records within a defined radius. Also, you can easily enhance the functionality of our radius based search as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

3 Comments

  1. Al Said...
  2. Jose M Vigo Said...
  3. Qamar Said...

Leave a reply

keyboard_double_arrow_up