Skip to Content
how to get nearby locations in php
php code / September 18, 2021

how to get nearby locations in php

The user can rapidly find specific data from a huge number of entries using the search tool. When a search request is made, the filtered data is usually retrieved from the database. The search feature can make the data list more user-friendly if you have a huge number of records.

To find data within a specified distance, a search based on latitude and longitude is utilised. For the most part, the property/store/place list is based on location. It allows you to find places 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.

We’ll use PHP and MySQL to provide the following functionality in the example script to showcase geographic searches within a specific radius.

Get the locations from the database and display them on the website.
Calculate the circumference of a circle using latitude and longitude.
The radius distance is used to find places.
Filtered data within a set radius is listed.

Make a database table.
In the MySQL database, we’ll build a locations table with some basic fields for this example. The records that will be searched are stored in the locations table.

CREATE TABLE `places` (
`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',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Configuring the Database (dbConfig.php)
The dbConfig.php file is used to connect PHP and MySQL to the database. According to your database credentials, specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

// 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 to Find Records Based on Radius Distance:
Initially, PHP and MySQL are used to retrieve all of the records from the database.

The distance between the places is determined in the MySQL SELECT query based on the latitude and longitude of the searched location if a radius-based search request is made.
The records are retrieved in chronological order based on their distance.

// Include database configuration file 
require_once 'dbConfig.php'; 
// If search form is submitted 
$location = $_POST['location']; 
$latitude = $_POST['loc_latitude']; 
$longitude = $_POST['loc_longitude']; 
$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 '; 
$order_by = ' 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:

Within the search for, an HTML form is provided to input the specific location and distance.

We’ll use the autocomplete option to select a specific location for location input.
The radius distance will be selected using a dropdown menu.

<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>
<input type="submit" name="searchSubmit" value="Search" />

Google Maps JavaScript API:

To use Google Maps JavaScript API with Places Library to add autocomplete location features to the input field, you’ll need the following JavaScript.

<!-- jQuery library -->
<script src=""></script>
<!-- Google Maps JavaScript library -->
<script src=""></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;
document.getElementById('longitude').value = near_place.geometry.location.lng();
$(document).on('change', '#'+searchInput, function () {
document.getElementById('latitude').value = '';
document.getElementById('longitude').value = '';

Note that

the key argument of the Google Maps JavaScript API requires you to enter your Google Maps API key.

List of Data based on Radius
The places within this radius will be listed on the webpage based on the distance selected.

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 } ?> 
echo '<h5>Place(s) not found...</h5>'; 

Note :

Radius-based search is particularly beneficial for property lists where records must be found within a given radius. We utilised locations to search by distance in this sample code. However, you may use this script for any search where you want to filter records inside a certain radius. You may also easily customise the functionality of our radius-based search to meet your specific requirements.


PHPCODE © 2023