loading

How to Radius Based Location Search with PHP and MySQL

How to Radius Based Location Search with PHP and MySQL

How to Radius Based Location Search with PHP and MySQL

0 Sales

Free

The search tool enables the user to easily discover particular data from a huge number of entries. Whenever a query request has been made, the filtered data is usually retrieved from the database. If you have a big number of entries, the search tool can help you navigate the data list.

To find data within a specified distance, a search based on latitude and longitude is utilised. The location-based search is mostly utilised for the list of properties/stores/places. It allows you to discover locations within a certain radius. In this article, we'll teach you how to use PHP and MySQL to combine radius-based location search with latitude and longitude.

The following functionality will be implemented in the sample script to showcase geolocation searches within a specific radius using PHP and MySQL.

 - Retrieve the locations from the system database, them on the website.

 - Circle distance may be calculated using latitude and longitude.

 - The radius distance is used to search for locations.

 - List data that has been filtered within a given radius.

Create Database Table

In this tutorial, we will construct a location's table in the MySQL database with some basic columns. The records that will be searched are stored in the locations table.

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 script is being used to connect PHP and MySQL to the database. As per your database credentials, enter the username ($dbUsername), database host ($dbHost), name ($dbName), password ($dbPassword).

<?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); 
}

Query for Search:

Initially, all data are collected from the database using PHP and MySQL.

 - If a radius-based search request is submitted,

      - the distance between the locations is computed in the MySQL SELECT mainly depending on the latitude and longitude of the requested site.

      - The data are retrieved in the order of their distance.

Search Records Based on Radius Distance

Search Query:

Originally, PHP and MySQL are used to get all of the records from the database.

 - If a radius-based query request is made,

      - The distance between the locations is determined in the MySQL SELECT mainly depending on the latitude and longitude of the requested location.

      - The data are retrieved in the order of their 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 given for entering the specific location and distance inside the search for.

 - We will be using the autocomplete area to choose a location for input.

 - A dropdown menu will be displayed to allow you to pick the 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 are examples: To add customizable technique to the input box employing Google Maps JavaScript API with Locations Library, JavaScript is necessary.

<!-- 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>

 

Data List Based on the Radius

The places inside this range will be displayed on the homepage based on the set distance.

<?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>'; 
} 
?>

 

Conclusion

Radius-based search is extremely beneficial for property lists where data must be searched within a specific distance. We utilised locations to seek by distance in this sample code. This script, however, may be used for any search where you wish to filter data inside a certain radius. You may also simply customise the functionality of our radius-based search to meet your specific requirements.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 24, 2022

Updated Date : Jan 24, 2022

Ratings

Comments : 0

Downloads : 0