Php obtains coordinates transmitted from the header of ios or android, obtains the specific city and address through the Baidu interface, and saves them to the session .,

Source: Internet
Author: User

Php obtains coordinates transmitted from the header of ios or android, obtains the specific city and address through the Baidu interface, and saves them to the session .,

First, encapsulate a method to obtain the header file in the function. php method file.

If (! Function_exists ('getallheaders ')){
Function getallheaders (){
$ Headers = array ();
Foreach ($ _ SERVER as $ name => $ value ){
If (substr ($ name, 0, 5) = 'HTTP _'){
$ Headers [str_replace ('', '-', ucwords (strtolower (str_replace ('_','', substr ($ name, 5)] = $ value;
}
}
Return $ headers;
}
}

Then, call this method in the corresponding controller to obtain data. First, check whether there is any location information in the session.

If (! $ _ SESSION ['mylocation'])
{
// Obtain the positioning Coordinate
$ Location = getallheaders ();
$ This-> get_location ($ location); // call the encapsulated Method
}

Finally, encapsulate a method to request the Baidu interface to return specific location information and coexist in the session.

Public function get_location ($ location)
{
$ Lat = $ location ['latitude '];
$ Lng = $ location ['longyun'];

If ($ lat & $ lng)
{
$ Url = 'HTTP: // api.map.baidu.com/geocoder/v2 /? Ak = 5BFNbSgnVF5g2O72NpvTDxFm & location = '. $ lat.', '. $ lng.' & output = json & pois = 1 ';
$ Html = json_decode (file_get_contents ($ url), true );

If ($ html)
{
$ MyLocation = array (
'City' => $ html ['result'] ['address'] ['city'],
'Addr '=> isset ($ html ['result'] ['address'] ['street'])? $ Html ['result'] ['address'] ['street']: $ html ['result'] ['formatted _ address'],
'Lng '=> $ html ['result'] ['location'] ['lng'],
'Lat' => $ html ['result'] ['location'] ['lat'],
);

$ _ SESSION ['mylocation'] = $ MyLocation;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.