Through the open API of Gaode map, real-time weather can be obtained according to IP positioning


A real-time weather display problem was encountered in the recent project. It was solved through the open API of Gaode map;
Leave your thoughts behind
It has been encapsulated into a function. It can be used directly. However, it’s best to test it before use;

First, by calling the API of Gaode map IP location;

The obtained IP location information contains addode; (it seems to be a group of urban geographic information numbers of Gaode)

Then call the API of Gaode's weather query;
Combine the adcode obtained from the previous IP location with your key;

Use steps of this class
Apply for a web secret key on Gaode’s official website. Then instantiate an object. Call the method info. Fill in the parameters of the method with the secret key you applied for. The return value is the weather of your current IP location;


class nansongWeather{

    //Get weather information
    public function info($key)
                                         //$key = 'the secret key you applied for in Gaode';
        $ipInfo = $this->ipInfo($key);  // Call the method to obtain IP location information;
        $city = $ipInfo->adcode;        // Get the adcode;
        $weatherInfo = $this->weatherInfo($key, $city); // Weather information has been obtained;
        return $weatherInfo;

    //Location information
    public function ipInfo($key)
            $ch = curl_init("".$key);
            curl_ setopt($ch, CURLOPT_RETURNTRANSFER, 1);    //  The requested data is not sent directly to the browser
            $result = curl_ exec($ch);    // Execute the request and send it directly to the browser
            // $city = json_decode($result)->adcode;
            $info = json_decode($result);
            return $info;
    //Weather information
        public function weatherInfo($key, $city)
            $ch = curl_init("" . $city ."&key=" . $key);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($ch);
            $info = json_decode($result)->lives[0];
            return $info;

The result is as shown in the figure. Note: the object is obtained
Through the open API of Gaode map, real-time weather can be obtained according to IP positioning

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]