AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Radius Based Location Search with PHP and MySQL

Create Database Table

Lakshika Mathur by Lakshika Mathur
December 21, 2019
Reading Time: 5 mins read
0
Radius Based Location Search with PHP and MySQL

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.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

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

Tags: PHP and MySQLRadius Location
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
83
Next Post
Ajax File Upload using jQuery and PHP

Ajax File Upload using jQuery and PHP

Upload Multiple Images and Store in Database using PHP and MySQL

Upload Multiple Images and Store in Database using PHP and MySQL

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version