In modern social applications, finding nearby users has become a popular and essential feature. Whether for making friends, joining interest groups, or recommending local services, this functionality enhances user experience. This article explains how to implement it using PHP and frontend technologies.
To find nearby users, the first step is to access their geolocation. The HTML5 Geolocation API allows browsers to retrieve latitude and longitude coordinates, and most modern browsers support it.
Before using the API, it's important to check whether the browser supports it:
if (navigator.geolocation) {
// Geolocation is supported
} else {
// Geolocation is not supported
}
If supported, you can then fetch the user's location.
Use the following code to retrieve and optionally send the coordinates to your backend:
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude; // Latitude
var longitude = position.coords.longitude; // Longitude
// Send coordinates to backend
// sendLocationToServer(latitude, longitude);
});
Once the user's location is retrieved, it needs to be stored in a database for later use. MySQL is a common choice for managing such data.
Create a users table to store coordinates:
CREATE DATABASE nearby;
USE nearby;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
latitude DOUBLE,
longitude DOUBLE
);
Here’s a PHP snippet to insert the coordinates into the database:
<?php
// Connect to the database
$conn = new PDO("mysql:host=localhost;dbname=nearby", "root", "");
// Retrieve latitude and longitude
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
// Insert into the database
$sql = "INSERT INTO users (latitude, longitude) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->execute([$latitude, $longitude]);
echo "Location saved successfully!";
?>
Once multiple users' coordinates are stored, you can calculate the distance between them to find those nearby. Below are two common methods.
This method is simple and useful for small-scale maps:
distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)
Use this when precision is not critical.
This formula provides more accuracy for calculating distances on a spherical surface like Earth:
distance = 2 * r * asin(sqrt(
sin((lat2 - lat1) / 2)^2 +
cos(lat1) * cos(lat2) * sin((lng2 - lng1) / 2)^2
))
Here, r represents Earth’s radius, typically set as 6371 km.
With these steps, you can build a PHP-based feature to find nearby users. From retrieving geolocation on the frontend to storing it in a database and calculating distance using precise formulas, the solution can be integrated into social apps, location-based services, and more. For large-scale use, consider performance optimization using caching or spatial indexing.