The search feature permits the user to find specific data from a vast number of records rapidly. Usually, when we submit the search request, the filtered data is fetched from the database. Therefore, if you have an enormous amount of records, the search feature can create the data list user-friendly.
The Search grounded on the latitude and longitude is used to find the records within a certain distance. Mostly, we have to use the location-based Search for the property/store/place list. Therefore, It will permit us to discover the places within a given radius. In this tutorial, we will explain to you how to assimilate radius based location search with latitude & longitude using MySQL and PHP.
In the example script, we will implement the following functionality to display geographic searches within a defined scope with PHP and MySQL.
- Get locations from the database and list them on the webpage.
- Calculate circle distance, which is based on latitude and longitude.
- The distance radius is based on the search place
- List filtered data within a defined radius.
Create Database Table
For instance, we will make a places
table with some primary fields in the MySQL database. Therefore, The places
table has 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)
Use thedbConfig.php
file to connect the database using PHP and MySQL. Specify the database host ($dbHost
), password ($dbPassword
) username ($dbUsername
), and name ($dbName
) as per your database credentials.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "allsweb"; // 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:
Firstly, Fetch all the records from the database with MySQL and PHP.
- If radius based search request is submitted,
- Based on the latitude and longitude of the searched location, we have to calculate the distance of the places 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 a specific location and distance within the Search.
- For location input, we will use the autocomplete field to select a particular place.
- Place a dropdown 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>
SEE ALSO: Ajax File Upload using jQuery and PHP
Google Maps JavaScript API:
The following JavaScript is essential to attach autocomplete location features to the input field by using the Google Maps JavaScript API with the location 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: You have to specify your Google Maps API key in the critical parameter of the Google Maps JavaScript API.
SEE ALSO: Forgot Password Recovery (Reset) using PHP and MySQL
Data List Based on the Radius
Based on the selected distance, List the places located within this radius 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>'; } ?>
Conclusion
Firstly, Search based on radius is easy to list property where we have to search for records within a certain distance. Secondly, in the example code, we have used locating locations. Thirdly, we will use this script for searches where you want to filter records within a defined scope. At last, you can easily enhance our radius-based search functionality to suit your needs.
Also, read our previous blog- Geolocation from IP Address using PHP