Home Backend Development PHP Tutorial Use longitude and latitude to determine which stores are closest to customers within a certain range, such as which stores are closest to a certain store within 1,000 meters.

Use longitude and latitude to determine which stores are closest to customers within a certain range, such as which stores are closest to a certain store within 1,000 meters.

Aug 08, 2016 am 09:27 AM
address data quot

Recently, the company needs to use the customer's delivery address to check which stores are closest to the customer's address. Customers can go to the nearest store to pick up the goods.

So how do we calculate which stores are within 1000 meters of the customer's address? We can use the following

1. Get the longitude and latitude of the customer's address, we can get it through the interface provided by Baidu Map. ($address is the customer address)

    //百度接口获取经纬度
    public function getlat($address) {
        $url = 'http://api.map.baidu.com/geocoder/v2/?city=上海&address=' . $address . '&output=json&ak=' . $this->ak;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data, true);
        $ret['lat'] = $data['result']['location']['lat'];
        $ret['lng'] = $data['result']['location']['lng'];
        echo json_encode($ret);
    }
Copy after login

2. If it is a store within 1000 meters, we need to calculate the distance within 1000 meters The longitude and latitude range.

    /*
     * 计算经纬度范围
     * $lat 纬度
     * $lon 经度
     * $raidus 半径(米)
     */

    function getAround($lat, $lon, $raidus) {
        $PI = 3.14159265;
        $EARTH_RADIUS = 6378137;
        $RAD = $PI / 180.0;

        $latitude = $lat;
        $longitude = $lon;
        $degree = (24901 * 1609) / 360.0;
        $raidusMile = $raidus;
        $dpmLat = 1 / $degree;
        $data = array();
        $radiusLat = $dpmLat * $raidusMile;
        $minLat = $latitude - $radiusLat;
        $maxLat = $latitude + $radiusLat;
        $data["maxLat"] = $maxLat;
        $data["minLat"] = $minLat;
        $mpdLng = $degree * cos($latitude * ($PI / 180));
        $dpmLng = 1 / $mpdLng;
        $radiusLng = $dpmLng * $raidusMile;
        $minLng = $longitude - $radiusLng;
        $maxLng = $longitude + $radiusLng;
        $data["maxLng"] = $maxLng;
        $data["minLng"] = $minLng;
        //print_r($data);
        return $data;
    }
Copy after login

3. We know that each store in the database stores the longitude and latitude information of this store. Now we can use the longitude and latitude range calculated above to query which stores are within 1000 meters.

    //计算出半径范围内的店
    public function getdz($lat, $lng) {
        include_once('my_db.php');
        $this->qu = new MY_DB_ALL("QUICK");
        //$ret = json_decode($this->getlat($address), true);
        //print_r($ret);exit;
        $data = $this->getAround($lat, $lng, 2000);
        //print_r($data);
        $sql = "select * from shop where baidu_lat between '" . $data['minLat'] . "' and '" . $data['maxLat'] . "' and baidu_lng between '" . $data['minLng'] . "' and '" . $data['maxLng'] . "' and status=1 and ztd_flag=2";
        $rett = $this->qu->rquery($sql);
        for ($i=0;$i<count($rett);$i++) {
            $array[$i]["shop_id"] = $rett[$i]["shop_id"];
            $array[$i]["shop_name"] = iconv("gbk","utf-8",$rett[$i]["shop_name"]);
            $array[$i]["shop_address"] = iconv("gbk","utf-8",$rett[$i]["shop_address"]);
            $array[$i]["shop_date"] = $rett[$i]["shop_date"];
            $array[$i][&#39;shop_phone&#39;] = $rett[$i]["shop_phone"];
            $array[$i][&#39;area&#39;] = $rett[$i]["area"];
        }
        //echo "<pre class="brush:php;toolbar:false">";print_r($array);exit;
        echo json_encode($array);
    }
Copy after login

Above The code needs to be written according to your actual situation. You can mainly look at the SQL statement $sql. Hehe

4. If I want to calculate which store is closest to the customer's address, I need a method to calculate the distance, as follows:

    /**
     *  @desc 根据两点间的经纬度计算距离
     *  @param float $lat 纬度值
     *  @param float $lng 经度值
     */
    public function getDistance($lat1, $lng1, $lat2, $lng2) {
        $earthRadius = 6367000; //地球半径

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;

        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }
Copy after login

5. Finally, we can know the closest store by calculating and comparing the minimum distances of the stores within 1000 meters. Which store is it?
    //计算出最近的一家店
    public function zjd($address) {
        $ret = $this->getdz($address);
        $jwd = $this->getlat($address);
        if ($ret) {
            $arr = array();
            foreach ($ret as $k => $v) {
                $arr[$k] = $this->getDistance($jwd['lat'], $jwd['lng'], $v['baidu_lat'], $v['baidu_lng']);
            }
            asort($arr);
            //print_r($arr);
            foreach ($arr as $k1 => $v1) {
                $data[] = $ret[$k1];
            }
            print_r($data);
        } else {
            echo '无最近的门店';
        }
    }
Copy after login

The above introduces how to determine which stores are closest to customers within a certain range through longitude and latitude, such as which stores are closest to a certain store within 1000 meters, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

What data is in the data folder? What data is in the data folder? May 05, 2023 pm 04:30 PM

The data folder contains system and program data, such as software settings and installation packages. Each folder in the Data folder represents a different type of data storage folder, regardless of whether the Data file refers to the file name Data or the extension. Named data, they are all data files customized by the system or program. Data is a backup file for data storage. Generally, it can be opened with meidaplayer, notepad or word.

What to do if mysql load data is garbled? What to do if mysql load data is garbled? Feb 16, 2023 am 10:37 AM

The solution to the garbled mysql load data: 1. Find the SQL statement with garbled characters; 2. Modify the statement to "LOAD DATA LOCAL INFILE "employee.txt" INTO TABLE EMPLOYEE character set utf8;".

What are the differences between xdata and data What are the differences between xdata and data Dec 11, 2023 am 11:30 AM

The differences are: 1. xdata usually refers to independent variables, while data refers to the entire data set; 2. xdata is mainly used to establish data analysis models, while data is used for data analysis and statistics; 3. xdata is usually used for regression Analysis, variance analysis, predictive modeling, data can be analyzed using various statistical methods; 4. xdata usually requires data preprocessing, and data can contain complete original data.

More returns than sales: The Humane Ai Pin is becoming a commercial disaster More returns than sales: The Humane Ai Pin is becoming a commercial disaster Aug 08, 2024 pm 01:14 PM

Shortly after the launch of the Humane Ai Pin, scathing reviews revealed that the AI gadget was anything but ready for the market, as most of the originally advertised features either didn't work properly or were simply missing, the battery life was

Can't data in vue component be a function? Can't data in vue component be a function? Dec 19, 2022 pm 05:22 PM

No, data in the vue component must be a function. Components in Vue are used for reuse. In order to prevent data reuse, they are defined as functions. The data data in the vue component should be isolated from each other and not affect each other. Every time the component is reused, the data data should be copied once. Later, when the data data in the component is changed in a reused place, other data will be copied. If the data data of reused local components is not affected, you need to return an object as the status of the component through the data function.

AI project failure rates top 80% — study cites poor problem recognition and a focus on latest tech trends among major problems AI project failure rates top 80% — study cites poor problem recognition and a focus on latest tech trends among major problems Aug 31, 2024 am 12:59 AM

Everyone and their aunt seem to be hopping aboard the AI train in search of inflated profit margins and marketing hype — just look at AMD's recent Ryzen rebrand as a prime example of this AI hype. A recent study conducted by RAND has found that this

MySQL writes crazy error logs MySQL writes crazy error logs Feb 18, 2024 pm 05:00 PM

A core business database, the version is MySQL8.34 Community Server Edition. Since its launch, the error log of this database server has increased very rapidly (as shown in the figure below), and can increase to more than 10 G in capacity every 24 hours. Because there was a fault alarm and normal access to the business had not been affected, the relevant personnel were not allowed to restart the MySQL service. In view of this situation, I had to set up an automatic scheduled task to clean these logs at a fixed time every night. For specific operations, execute "crontab -e" on the system command line and add the following text line: 0001***echo>/data/mysql8/data/mysql_db/mysql.log Save and exit edit mode

See all articles