php - Converting City&Country to Coordinate points -
is there fast php code convert city + country latitude , longitude coordinates. have list of locations , need convert them coordinates. tried doing in javascript, encountered problems trying results php store in json file. there efficient php code this?
thanks.
in app, i'm using following function geo-code locations using google service. function takes 1 parameter - location
geo-code (e.g. "boston, usa" or "sw1 1aa, united kingdom") , returns associative array lat/lon. if error occurs or location cannot determined, returns false.
note in many cases city + country not able determine location uniquely. example, there 100 cities named springfield in usa alone. also, when passing country geo-coding service, make sure put full country name , not 2-letter code. found hard way: passing 'ca' "canada" , getting strange results. apparently, google assumed 'ca' means "california".
function getgeolocationgoogle($location) { $url = "http://maps.googleapis.com/maps/api/geocode/xml?address=". urlencode($location) . "&sensor=false"; $useragent = "mozilla/5.0 (x11; u; linux i686; en-us; rv:1.9.2) gecko/20100115 firefox/3.6 firephp/0.4"; //setup curl object , execute $curl = curl_init($url); curl_setopt($curl, curlopt_useragent, $useragent); curl_setopt($curl, curlopt_failonerror, true); curl_setopt($curl, curlopt_returntransfer, 1); $result = curl_exec($curl); $req = $location; //process response google servers if (($error = curl_errno($curl)) > 0) { return false; } $geo_location = array(); //try convert xml response object try { $xmldoc = new domdocument(); $xmldoc->loadxml($result); $root = $xmldoc->documentelement; //get errors $status = $root->getelementsbytagname("status")->item(0)->nodevalue; if($status != "ok") { $error_msg = "could not determine geographical location of $location - response code $status"; } $location = $root->getelementsbytagname("geometry")->item(0)->getelementsbytagname("location")->item(0); if(!$location) { return false; } $xmllatitude = $location->getelementsbytagname("lat")->item(0); $valuelatitude = $xmllatitude->nodevalue; $geo_location['latitude'] = $valuelatitude; //get longitude $xmllongitude = $location->getelementsbytagname("lng")->item(0); $valuelongitude = $xmllongitude->nodevalue; $geo_location['longitude'] = $valuelongitude; //return location - measure $geo_location['location'] = $req; } catch (exception $e) { return false; } return $geo_location; }
Comments
Post a Comment