php/mysql zip code proximity search

前端 未结 7 1993
南笙
南笙 2020-12-02 15:08

I\'m just looking for suggestions on the best way to do this...

I need to create a search function that searches for \"users\" within a 50 mile radius of a zip code

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 15:30

    Here is the best way I have found. Of course it will require that you have all of your zipcodes lat/lon encoded in the database.

    // get all the zipcodes within the specified radius - default 20
    function zipcodeRadius($lat, $lon, $radius)
    {
        $radius = $radius ? $radius : 20;
        $sql = 'SELECT distinct(ZipCode) FROM zipcode  WHERE (3958*3.1415926*sqrt((Latitude-'.$lat.')*(Latitude-'.$lat.') + cos(Latitude/57.29578)*cos('.$lat.'/57.29578)*(Longitude-'.$lon.')*(Longitude-'.$lon.'))/180) <= '.$radius.';';
        $result = $this->db->query($sql);
        // get each result
        $zipcodeList = array();
        while($row = $this->db->fetch_array($result))
        {
            array_push($zipcodeList, $row['ZipCode']);
        }
        return $zipcodeList;
    }
    

    You should be able to just drop in this function. Pass it the $lat and $lon of the zipcode you want the radius for, include the optional radius, and get a list of zipcodes back.

    You could very easily modify this to get all users where zipcode IN (radius_sql) and get your list users back.

    Happy Coding!

提交回复
热议问题