Skip to content

Instantly share code, notes, and snippets.

@stsibel
Last active September 26, 2022 18:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stsibel/41c3f52b931d948c1548 to your computer and use it in GitHub Desktop.
Save stsibel/41c3f52b931d948c1548 to your computer and use it in GitHub Desktop.
MySQL query to find zip-codes within given radius from any point (or zip-code)
/* Given table 'zipcodes' with columns:
zipcode, latitude, longitude.
Find zipcodes within radius from given zipcode.
EXAMPLE:
Coordinates for zip 91326 and radius 25 mi:
*/
SET @location_lat = 34.2766,
@location_lon = -118.544;
SELECT zipcode, ( 3959 * acos( cos( radians(@location_lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(@location_lon) ) + sin( radians(@location_lat) ) * sin( radians( latitude ) ) ) ) AS distance
FROM zipcodes
HAVING distance < 25;
/*
Result:
+-------------+-------------------+
| zipcode | distance |
+-------------+-------------------+
| 90004 | 19.32764527143567 |
| 90005 | 20.34491933480445 |
| 90006 | 21.56930375425860 |
| ... | ... |
+-------------+-------------------+
*/
@stsibel
Copy link
Author

stsibel commented Sep 17, 2014

@vinaeoua
Copy link

vinaeoua commented Jun 17, 2019

<?php
		$host_name = 'localhost';
		$database = 'db1';
		$user_name = 'root';
                $password = 'pswd';
                    $zipcode = $_POST['zipcode'];
                    $distance = $_POST['distance'];
                    
                    // Create connection
                    $conn = new mysqli($host_name, $user_name, $password, $database);
                    // Check connection
                    if ($conn->connect_error) {
                        die("Connection failed: " . $conn->connect_error);
                    } 
                    $sql = "SELECT * FROM zipcodeus WHERE zipcode = '$zipcode'";
                    $result = $conn->query($sql);

                    if ($result->num_rows > 0) {
                        // output data of each row
                       while($row = $result->fetch_assoc()) {
                            $lat1 = $row["latitude"];
                            $lon1 = $row["longitude"];
                           // echo 
                          //  "zipcode: " . $row["zipcode"]. 
                         //  "latitude: " . $row["latitude"]. 
                         //   "longitude: " . $row["longitude"]. 
                         //   " - city: " . $row["city"]. 
                          //  " - state: " . $row["name_state"]. "<br>";
                            }
                    } else {
                        echo "0 results";
                    }
                    $query = "SELECT *, ( 3959  * acos( cos( radians($lat1) ) 
                                                * cos( radians( latitude ) ) 
                                                * cos( radians( longitude ) 
                                                - radians($lon1) ) 
                                                + sin( radians($lat1) ) 
                                                * sin( radians( latitude ) ) ) ) 
                                                AS distance
                        FROM zipcodeus
                        HAVING distance < $distance;";
                        $print = $conn->query($query);

                        if ($print->num_rows > 0) {
                            // output data of each row
                            while($row = $print->fetch_assoc()) {
                                echo "zipcode: " 
                                . $row["zipcode"]. "latitude: " 
                                . $row["latitude"]. "longitude: " 
                                . $row["longitude"]. " - city: " 
                                . $row["city"]. " - state: " 
                                . $row["name_state"]. "<br>";
                            }
                        } else {
                            echo "0 results";
                        }
                        $conn->close();
                ?>

`
Live test
@vinaeoua

@sujit-thoughti
Copy link

what is 3959

@stsibel
Copy link
Author

stsibel commented Sep 10, 2019

@sujit-thoughti very good question. 3959 is the radius of our planet (Earth) in miles according to IUGG standard. You can read more about it here: https://en.wikipedia.org/wiki/Earth_radius.

P.S. If you will even have to get list of zip codes within a specific distance on the Mars, you can replace 3959 with 2106.1

@dpareek10
Copy link

dpareek10 commented Aug 26, 2021

Hey, I tried this formula with ZipCode 39564:
@location_lat = 30.400640,
@location_lon = -88.758255

and it gives me this error:
image

It runs fine with the others that I've tested. Any idea why?
Thanks!

PS: I Rounded up to 5 decimal points in the formula and it worked, the precision decreased just a bit.

@ajayvd
Copy link

ajayvd commented Sep 26, 2022

@stsibel SELECT zipcode, ( 3959 * acos( cos( radians(@location_lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(@location_lon) ) + sin( radians(@location_lat) ) * sin( radians( latitude ) ) ) ) AS distance FROM zipcodes HAVING distance < 25;

could you please tell me what value do i need to place in latitude? do we need to pass the same value which we are assigning in set operation.

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment