Google map API with PHP to achieve login Map location

Source: Internet
Author: User
Tags floor function fread get ip ip number ord
Google map API with PHP to achieve login map location

Google Map API in combination with PHP to achieve the main idea is to log the user log on the system when the IP address, in the relevant address index from the IP to the physical address, and finally through the Google Map API will be obtained by the physical address marked on Google Maps.

?

The PHP platform is built from the thinkphp framework. The specific flowchart is as follows:


?

Here to use the Coralwry this data file, online some download, the previous rainbow QQ or anything is used this file parsing, but may sometimes need to update the IP for the sake of this file will be updated, the following download package. This file is placed in the root directory

?

continue, in TP introduced a two files as a chain call library, you can directly into the TP core folder in the Org extension library under the Lib

Iplocation class, this extension class is used to extract IP addresses from the DAT file

?

Class Iplocation {var $fp; var $firstip;   The offset address of the first IP index is var $lastip;  The last IP index offset address var $totalip; Total IP number//*//constructor, initialize some variables//$datfile The value is the name of the pure IP database, you can modify it yourself.//*function iplocation ($datfile = "CoralWry.Dat") {$this   Fp=fopen ($datfile, ' RB ') or Die ("CoralWry.Dat does not exist, please go online to download the pure IP database, ' CoralWry.dat ' put in the current directory"); Binary mode open $this->firstip = $this->get4b ();  The absolute offset address of the first IP index $this->lastip = $this->get4b (); The absolute offset address of the last IP index $this->totalip = ($this->lastip-$this->firstip)/7;  The IP total index area is a fixed length of 7 bytes, which is divided by 7, register_shutdown_function (Array ($this, "CLOSEFP")); To be compatible with the following versions of PHP5, this class does not use destructors to automatically close IP libraries.} *//Close IP Library//*function closefp () {fclose ($this->fp);}  *//reads 4 bytes and extracts the long mode//*function get4b () {$str =unpack ("V", Fread ($this->fp,4)); return $STR [1];}  *//Read redirected offset address//*function getoffset () {$str =unpack ("V", Fread ($this->fp,3). chr (0)); return $STR [1];}  *//Read IP address details//*function getstr () {$str = "";  $split =fread ($this->fp,1); while (Ord ($split)!=0) {$str. = $split; $split =frEAD ($this->fp,1); } return $str;} *//the IP via ip2long to IPv4 's Internet address, then compresses him into Big-endian byte order//used to compare with the IP address in the index area//*function iptoint ($IP) {return Pack ("N", Intval (Ip2long ($IP)));} *//Get client IP address//NOTE: If you want to log the IP to the server, check that the IP data is secure when you write the library.//*function GetIP () {if (getenv (' http_client_ip ')) {$ip = g Etenv (' http_client_ip '); }elseif (getenv (' http_x_forwarded_for ')) {//Get the real IP address of the client when accessing the proxy server $ip = getenv (' http_x_forwarded_for ');} ElseIf (getenv (' http_x_forwarded ')) {$ip = getenv (' http_x_forwarded ');} ElseIf (getenv (' http_forwarded_for ')) {$ip = getenv (' http_forwarded_for ');} ElseIf (getenv (' http_forwarded ')) {$ip = getenv (' http_forwarded ');} else {$ip = $_server[' remote_addr ');} return $IP;}  *//get address information//*function readaddress () {$now _offset=ftell ($this-&GT;FP);//Get current pointer-address $flag = $this->getflag (); Switch (ord ($flag)) {case 0: $address = ""; 1:case 2:fseek ($this->fp, $this->getoffset ()) ; $address = $this->getstr (); Break Default:fseek ($this->fp, $now _offSet); $address = $this->getstr ();  Break } return $address;} *//gets the flag 1 or 2//used to determine whether the address is redirected.//*function Getflag () {return fread ($this->fp,1);}     *//searching in the index area using binary search method ip//*function searchip ($ip) {$ip =gethostbyname ($IP);  Turn the domain name into an IP $ip _offset["IP"]= $ip;    $ip = $this->iptoint ($IP);                 Convert IP to growth integer $firstip = 0;     Top boundary of search $lastip = $this->totalip;    Bottom boundary $ipoffset of search = $this->lastip;          The offset address initialized to the last IP address while ($firstip <= $lastip) {$i =floor ($firstip + $lastip)/2);    Calculate approximate intermediate records the floor function calculates the largest integer of a given floating-point number, which is plainly the fseek ($this->fp, $this->firstip + $i * 7);         Position the pointer to the intermediate record $startip=strrev (fread ($this->fp,4)); Reads the start IP address in the current index area and converts its Little-endian byte order to Big-endian's byte order if ($ip < $startip) {$lastip = $i-1;}   else {fseek ($this->fp, $this->getoffset ());   $endip =strrev (fread ($this->fp,4));   if ($ip > $endip) {$firstip = $i + 1;      } else {$ip _offset["offset"]= $this->firstip + $i * 7;   Break }}} return $ip _Offset;}  *//Get IP Address details//*function getaddress ($ip) {$ip _offset= $this->searchip ($IP);  Gets the absolute address of the IP within the index area $ipoffset = $ip _offset["offset"];  $address ["IP"]= $ip _offset["IP"];      Fseek ($this->fp, $ipoffset); Navigate to the index area $address ["StartIP"]=long2ip ($this->get4b ());            The start IP address within the index area $address _offset= $this->getoffset ();            Gets the offset address fseek ($this->fp, $address _offset) of IP within the index area within the IP record area;   Locate the $address in the recording area ["EndIP"]=long2ip ($this->get4b ());                      End IP address in the record area $flag = $this->getflag ();   Read Flag byte switch (ORD ($flag)) {Case 1://Region 1 Region 2 are redirected $address _offset= $this->getoffset ();     Read REDIRECT Address fseek ($this->fp, $address _offset);               Position the pointer to the redirected address $flag = $this->getflag (); Read Flag byte switch (ORD ($flag)) {Case 2://Region 1 redirect again, fseek ($this->fp, $this->getoffset ()); $address ["Area1"]= $th      Is->getstr (); Fseek ($this->fp, $address _offset+4);  Jump 4 bytes $address["area2"]= $this->readaddress (); Region 2 There may be redirects, there may be no break;deFault://Region 1, Region 2 no redirect fseek ($this->fp, $address _offset); Position the pointer to the redirected address $address["area1"]= $this->getstr (); $address ["Area2"]= $this->readaddress (); break; } break;   Case 2://Region 1 REDIRECT Region 2 No redirect $address 1_offset= $this->getoffset ();   Read REDIRECT Address fseek ($this->fp, $address 1_offset); $address ["area1"]= $this->getstr (); Fseek ($this->fp, $address _offset+8); $address ["Area2"]= $this->readaddress (); Break Default://Region 1 Region 2 no redirect fseek ($this->fp, $address _offset+4); $address ["area1"]= $this->getstr (); $address ["Area2"]= $this->readaddress ();  Break  }//* filter Some useless data if (Strpos ($address ["area1"], "cz88.net")!=false) {$address ["area1"]= "Unknown";  } if (Strpos ($address ["area2"], "cz88.net")!=false) {$address ["area2"]= ""; } return $address;  }}

?

?

MaPservice class, Method class

?

?

/** * Google Map Service * 2011.4.8 */import ("ORG. Ipa. Iplocation "), class Mapservice{public static function Getipaddress ($IP) {//return format $format =" text ";//Default text,json,xml,js// return encoding $charset = "UTF8"; Default UTF-8,GBK or Gb2312$ip_l=new iplocation (), $address = $ip _l->getaddress ($ip), $address ["area1"] = Iconv (' GB2312 ', ' Utf-8 ', $address ["area1"]), $address ["area2"] = Iconv (' GB2312 ', ' utf-8 ', $address ["area2"]); $add = $address ["Area1"]. $address ["Area2"];if ($add = = "Native Address") {$add = "Hangzhou";} return  $add;}}
?

You can then invoke the two file classes in the Login action interface function:

?

?

Import ("ORG. Ipa. Mapservice ");        $ipaddress = Get_client_ip (); $adrInfo =mapservice::getipaddress ($ipaddress);
?

?

The above information can then be recorded in the database, and when the user enters the map page, the data can be exported from the database and sent to the view layer for display, and the Google Map API is called at the front-end layer

?

The background control layer code is simple:

?

?

Public Function Map () {parent::islogin (); $model = D ("Topicview");        $list =  $model->field (' Id,tid,imgid,avatar,address,create_time,topic_from,content,nickname,rootid, Homepage ')        ->where ("Topic.status=1 and topic.type= ' first '")        ->order ("id desc")->find ();//dump ($ list), $this->assign (' addrlist ', $list);p arent::showsiteinfo ("Lab Front lab-Map Position");        $this->display ();        }
?

?

Next is the foreground template layer JS code:

?

?

if (typeof Flowg = = "undefined" | |!flowg) {var flowg = {};} Flowg.initmap = (function () {var htmlstring = ' + ' + ' + ' + ' + ' + ' {$addrList. Nickname}: {$addrList. Co    ntent} ' + ' He is in {$addrList. Address} ' + ' + ';    var Geocoder;    var map;    var oldinfo = null;        function Initialize () {geocoder = new Google.maps.Geocoder ();        var latlng = new Google.maps.LatLng (34.016, 103.535);        var myoptions = {zoom:8, center:latlng, MapTypeId:google.maps.MapTypeId.ROADMAP        };        Map = new Google.maps.Map (document.getElementById ("Map_canvas"), myoptions);    Codeaddress ("{$addrList. Address}", htmlstring); } function codeaddress (address, HTML) {Geocoder.geocode ({' Address ': address}, Function (r Esults, status) {if (status = = Google.maps.GeocoderStatus.OK) {Map.setcenter (results[0].geometr                Y.location); var marker = new Google.maps.MaRker ({map:map, position:results[0].geometry.location});                var contentstring = html;                var Infowindow = new Google.maps.InfoWindow ({content:contentstring});                Infowindow.open (map, marker);                if (oldinfo! = null) {oldinfo.close ();            } oldinfo = Infowindow;            } else {return false;    }        }); } return initialize;}) (); $ (FLOWG.INITMAP);
?

?

The above directly calls the Google Map marker feature to display the information:

?


  • 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.