Distance Calculator: Latitude & Longitude using PHP & MySQL


Geospatial Distance Calculator (Latitude/Longitude)

An advanced tool to calculate the great-circle distance between two points, with insights on implementing it with PHP and MySQL.

Calculate Distance



In decimal degrees (e.g., 40.7128)


In decimal degrees (e.g., -74.0060)


In decimal degrees (e.g., 34.0522)


In decimal degrees (e.g., -118.2437)



In-Depth Guide: Calculate Distance Using Latitude and Longitude PHP & MySQL

Calculating the distance between two geographical points is a fundamental requirement for a vast array of web applications, from store locators to complex logistical planning systems. The core challenge is to accurately measure the great-circle distance—the shortest path between two points on the surface of a sphere. This guide provides a comprehensive look into how to calculate distance using latitude and longitude php & mysql, leveraging the power of the Haversine formula for accuracy and server-side scripting for scalability.

What is Geospatial Distance Calculation?

Geospatial distance calculation involves determining the distance between two coordinates on the Earth. Unlike a flat plane where the Pythagorean theorem would suffice, the Earth’s curvature requires more complex spherical trigonometry. The most common and widely accepted method for this is the Haversine formula, which accounts for the planet’s spherical shape. When developers need to calculate distance using latitude and longitude php & mysql, they are typically looking to query a database of locations (stored in MySQL) and perform the distance calculation on the server-side (using PHP) to, for example, find all points within a certain radius.

The Haversine Formula and its PHP/MySQL Implementation

The Haversine formula is an equation that provides great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of the more general law of haversines in spherical trigonometry. This formula is crucial for any application that needs to calculate distance using latitude and longitude php & mysql accurately.

The formula is as follows:

`a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)`

`c = 2 ⋅ atan2(√a, √(1−a))`

`d = R ⋅ c`

Haversine Formula Variables
Variable Meaning Unit Typical Range
φ Latitude Radians -π/2 to +π/2
λ Longitude Radians -π to +π
Δφ, Δλ Difference in latitude and longitude Radians
R Earth’s radius km (6371) or miles (3959)
d The resulting distance km, miles, or nmi

Implementation in PHP

Here’s a standard PHP function to implement the calculation. This is the logic you would use on your server to process coordinates. A robust implementation would be a core part of any project involving PHP best practices for geospatial data.

function haversineGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371)
{
  // convert from degrees to radians
  $latFrom = deg2rad($latitudeFrom);
  $lonFrom = deg2rad($longitudeFrom);
  $latTo = deg2rad($latitudeTo);
  $lonTo = deg2rad($longitudeTo);

  $latDelta = $latTo - $latFrom;
  $lonDelta = $lonTo - $lonFrom;

  $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
    cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
  return $angle * $earthRadius;
}

Querying with MySQL

While you can fetch coordinates and calculate in PHP, for large datasets, it’s far more efficient to perform the calculation directly in MySQL. This is a key aspect of how to effectively calculate distance using latitude and longitude php & mysql. Since MySQL 5.7, the `ST_Distance_Sphere` function provides a highly optimized, native way to do this. For older versions, the Haversine formula can be implemented directly in the query. Check out our guide on MySQL performance analysis for more tips.

-- Using modern MySQL (5.7+) with ST_Distance_Sphere (meters)
SELECT
  name,
  ST_Distance_Sphere(
    point(lon, lat),
    point(-74.0060, 40.7128)
  ) AS distance_in_meters
FROM locations
HAVING distance_in_meters <= 10000; -- 10km radius

-- Implementing Haversine in a query for older MySQL
SELECT
  id,
  ( 6371 * acos( cos( radians(40.7128) ) * cos( radians( lat ) ) * 
  cos( radians( lon ) - radians(-74.0060) ) + sin( radians(40.7128) ) * 
  sin( radians( lat ) ) ) ) AS distance_in_km
FROM locations
HAVING distance_in_km < 10;

Practical Examples

Example 1: New York to Los Angeles

  • Input (Point 1 - NYC): Latitude: 40.7128, Longitude: -74.0060
  • Input (Point 2 - LA): Latitude: 34.0522, Longitude: -118.2437
  • Units: Kilometers
  • Result: Approximately 3940 km

This demonstrates a simple point-to-point calculation, useful for route planning or distance verification.

Example 2: Finding Nearby Stores with PHP & MySQL

A user provides their location (e.g., 37.7749, -122.4194). The goal is to find all stores within a 25km radius.

  1. The user's coordinates are sent to a PHP backend.
  2. PHP constructs a MySQL query using `ST_Distance_Sphere` to find matching locations.
  3. The query returns a list of stores, ordered by distance, which PHP then formats and sends back to the user. This is a common task in database optimization.

This real-world scenario is the primary reason developers search for how to calculate distance using latitude and longitude php & mysql.

How to Use This Geospatial Distance Calculator

  1. Enter Point 1 Coordinates: Input the latitude and longitude for your starting location in the first two fields.
  2. Enter Point 2 Coordinates: Input the latitude and longitude for your destination in the second two fields.
  3. Select Units: Choose your desired unit of measurement (Kilometers, Miles, or Nautical Miles) from the dropdown menu.
  4. Calculate: Click the "Calculate" button. The result will instantly appear below, showing the primary distance and intermediate values from the Haversine formula.
  5. Interpret Results: The main value is the great-circle distance. The intermediate values can be useful for debugging or for a deeper understanding of the Haversine implementation.

Key Factors That Affect Distance Calculation

  • Earth's Shape: The Haversine formula assumes a perfect sphere, but the Earth is an oblate spheroid (slightly flattened at the poles). For most applications, this introduces a negligible error (around 0.3-0.5%). For high-precision scientific needs, Vincenty's formulae are used.
  • Data Types in MySQL: Using `FLOAT` or `DOUBLE` for storing coordinates can lead to precision errors. The recommended type is `DECIMAL(10, 8)` for latitude and `DECIMAL(11, 8)` for longitude. For modern applications, the `POINT` spatial data type is preferred.
  • Computational Efficiency: Calculating distance for millions of records can be slow. Using native database functions like `ST_Distance_Sphere` is much faster than pulling data into PHP and calculating it there.
  • Database Indexing: To speed up "radius search" queries, a spatial index must be applied to the column storing coordinates. This is a critical optimization for any performant geospatial query in MySQL.
  • Unit Conversion: Ensure you are using a consistent radius for the Earth (e.g., 6371 for km, 3959 for miles) and correctly converting the final result if needed.
  • Input Data Accuracy: The accuracy of the output is directly dependent on the accuracy of the input coordinates.

Frequently Asked Questions (FAQ)

Why can't I just use a simple Pythagorean (x² + y² = z²) formula?

The Pythagorean theorem works on a flat, Euclidean plane. It does not account for the Earth's curvature, leading to significant errors over long distances.

How accurate is the Haversine formula?

It is generally accurate to about 0.5%. This is more than sufficient for most web applications but may not be suitable for high-precision scientific or aeronautical navigation.

What is the difference between `ST_Distance_Sphere` and `ST_Distance` in MySQL?

`ST_Distance_Sphere` calculates the distance on a spherical model of the Earth and returns the result in meters. `ST_Distance` calculates the simple Euclidean distance between two points in a spatial reference system, which is not what you want for geographic coordinates.

How should I store latitude and longitude in MySQL?

For MySQL 5.7+, use the native `POINT` data type. For older versions, use `DECIMAL` fields to avoid floating-point inaccuracies. For example: `lat DECIMAL(10, 8), lon DECIMAL(11, 8)`.

What is a spatial index and why do I need it?

A spatial index is a special type of database index that allows for efficient querying of spatial data. When you ask "find all points within 10km," a spatial index prevents the database from having to calculate the distance for every single row, dramatically speeding up the query. Creating a MySQL spatial distance query without an index on a large table will be extremely slow.

What units does this calculator support?

This calculator can provide the distance in Kilometers (km), Miles (mi), and Nautical Miles (nmi). You can switch between them using the dropdown menu.

Can this calculation be done entirely in the browser with JavaScript?

Yes, as this calculator demonstrates. The JavaScript on this page performs the same Haversine calculation. However, if your application needs to query a large database of locations, a server-side approach with PHP and MySQL is necessary.

Is there a server-side API for this?

While this page is self-contained, building a latitude longitude distance API is a common use case. It would involve creating a PHP endpoint that accepts coordinates and returns the calculated distance in JSON format.

© 2026 GeoCalculators Inc. All rights reserved.


Leave a Reply

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