Expedia EAN / TravelNow search using city name issue - php

I have implemented the EAN hotel search API using XML and PHP. And I have the following issue when searching and listing hotels.
Search details
City - Soho
Country - GB
Arrival - Aug 1, 2013
Departure - Aug 2, 2013
Rooms - 1 room with 2 adults
Results in TravelNow site
http://www.travelnow.com/templates/331656/hotels/list?lang=en&currency=GBP&secureUrlFromDataBridge=https%3A%2F%2Fwww.travelnow.com&requestVersion=V2&destination=&standardCheckin=8%2F1%2F2013&standardCheckout=8%2F2%2F2013&checkin=8%2F1%2F13& amp;checkout=8%2F2%2F13&rating=0&targetId=AREA-d5cfc783-9e42-4440-9200-0bd17397c37f%7Clandmarks&roomsCount=1&rooms[0].adultsCount=2&rooms[0].childrenCount=0&filter.sortedBy=our_rec&filter.hotelName=&filter.lowPrice=0&filter.travelerOpinion=0&filter.breakfastIncluded=false&subscriptionInfo.termsConditionAgreement=false&subscriptionInfo.wantNews=false&subscriptionInfo.wantNewsletters=false&tab=list
In TravelNow site, we searched for Soho, London, United Kingdom as shown in the above URL
Request sent
http://api.ean.com/ean-services/rs/hotel/v3/list?currencyCode=GBP&minorRev=99&apiKey=XXXXXXXXXXXXXXXXXXXXXXXX&locale=en_US&cid=XXXXXXXX&sort=OVERALL_VALUE&xml=<HotelListRequest><city>Soho<%2Fcity><countryCode>GB<%2FcountryCode><arrivalDate>08%2F01%2F2013<%2FarrivalDat e><departureDate>08%2F02%2F2013<%2FdepartureDate><numberOfResults>25<%2FnumberOfResults><supplierType>E%7CV<%2FsupplierType><supplierCacheTolerance>MED_ENHANCED<%2FsupplierCacheTolerance><RoomGroup><Room><numberOfAdults>2<%2FnumberOfAdults><%2FRoom><%2FRoomGroup><%2FHotelListRequest>
Response received
<ns2:HotelListResponse xmlns:ns2="http://v3.hotel.wsapi.ean.com/">
<EanWsError>
<itineraryId>-1</itineraryId>
<handling>UNKNOWN</handling>
<category>EXCEPTION</category>
<exceptionConditionId>-1</exceptionConditionId>
<presentationMessage>No Results Available</presentationMessage>
<verboseMessage>Result was null</verboseMessage>
<ServerInfo serverTime="05:45:17.821-0500" timestamp="1375181117" instance="54"/>
</EanWsError>
<customerSessionId>0ABAAA36-B023-AF91-4022-F2DA5EE95A74</customerSessionId>
</ns2:HotelListResponse>
I also searched with city string "Soho, London, United Kingdom" given for city/destinationString didn't list any hotel. We used API tester http://devhub.ean.com/apitester/index.html too and received the same results.
This search mostly says no results for many cities in London. We tried "destinationString" based search shown in http://developer.ean.com/docs/read/hotel_list/examples/XML_Alternatives but didn't work either. How do we need to pass the destination/city? Even when it shows hotels they are not in/around the given city.
Let us know how to implement the above request to work properly to list the hotels in a given city. This works only for a few cities we have listed in the search. Shown below is a list of exact city names in London we use to pass in the request, inside the block. If below city names are incorrect, then how do they need to be corrected?
Bayswater-Paddington,
Belgravia,
Bloomsbury-Soho,
Canary Wharf-Docklands,
Camden Town,
Chelsea,
Chelsea-Knightsbridge,
City of Westminster,
Chinatown,
East End,
Fulham,
Greenwich,
Holborn,
Hammersmith,
Hampstead,
Hampstead-Camden Town,
Hounslow,
Islington,
Knightsbridge,
Kensington,
Lambeth,
London,
London area,
Mayfair,
Mayfair-Marylebone,
Marylebone,
Pimlico,
St. Pancras - Islington,
Soho,
Southwark-Waterloo
Please help with a REST/XML request string that works for the above city/cities.
I haven't accepted any of the current answers but are looking for more correct answers that rings a bell.

I am using REST method for get hotel list
My code is given below
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?minorRev=14
&cid=55505
&apiKey=p9ycn9cxb2zp3k3gfvbf5aym
&customerUserAgent=&customerIpAddress=
&locale=en_US
&currencyCode=USD
&city=Lasvegas
&stateProvinceCode=NV
&countryCode=US
&supplierCacheTolerance=MED
&arrivalDate=08/25/2013
&departureDate=08/27/2013
&room1=2
&numberOfResults=25
&supplierCacheTolerance=MED_ENHANCED';
$header[] = "Accept: application/json";
$header[] = "Accept-Encoding: gzip";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = json_decode(curl_exec($ch));
$rt = curl_getinfo($ch);
echo "<pre>";
print_r($response);
echo "</pre>";
You want more details.
See this links

You have to use geoSearch tab given at api tester by ean:
http://devhub.ean.com/apitester/index.html
after that you have to insert destination string in that and fetch the city name according to the responce.
Here is the sample code how you have to do this:
$destination="soho";//YOUR Destination string
$Geosearch='https://api.eancdn.com/ean-services/rs/hotel/v3/geoSearch?cid=50555&minorRev=99&apiKey=**XXXXX(your_api_key)**&locale=en_US&currencyCode=USD&xml=%3CLocationInfoRequest%3E%0A%20%20%20%20%3Clocale%3Een_US%3C%2Flocale%3E%0A%20%20%20%20%3CdestinationString%3E';
$Geosearch.=$destination;
$Geosearch.='%3C%2FdestinationString%3E%0A%3C%2FLocationInfoRequest%3E';
$locate = json_decode(file_get_contents($Geosearch),true);
$citynames=$locate['LocationInfoResponse']['LocationInfos']['LocationInfo'];
$citysearched=$citynames['city'];
Now you have to use hotel list url and concatinate $citysearched value instead of your destination string.

You may using file_get_contents
below are the code
$request = "http://dev.api.ean.com/ean-services/rs/hotel/v3/list";
$minorRev = "20";
$cid = "55505";
$api = "p9ycn9cxb2zp3k3gfvbf5aym";
//room available
$response = file_get_contents($request . '?minorRev=' . $minorRev . '&cid=' . $cid . '&apiKey=' . $api . '&locale=en_US&currencyCode=MYR&hotelId='. $hotel_id . '&arrivalDate=' . $arrivalDate . '&departureDate=' . $departureDate . $room . '&includeDetails=true&includeRoomImages=true&options=HOTEL_DETAILS,ROOM_TYPES,ROOM_AMENITIES,HOTEL_IMAGES');
$result = json_decode($response, false);
By the way the api link should be http://dev.api.ean.com/

I got same issue, Finally found issue with whitespace (\n \r). You can remove whitespace using below method.
function prepare_xml($xml=""){
$xml = preg_replace('/\s+/', ' ',$xml);
$xml = str_replace("> <","><",$xml);
return $xml;
}

Related

Curl is not giving json response in php

I am trying to do api integration with a news providing website through curl.I am able to retrieve the data but it is not in json format so it is difficult to display that data on my portal.
Below is the code which i am using.
Please someone help
curl.php
<?php
function file_get_contents_curl()
{
$url='https://newsapi.org/v2/top-headlines?'.
'country=us&'.
'apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$content = false;
$headers = array('Content-Type:application/json');
if (function_exists('curl_init')) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 5);
$content = curl_exec($curl);
curl_close($curl);
}
return $content;
}
$result=file_get_contents_curl();
echo $result;
?>
Below is the result which i am getting if i echo the response received from above code
{"status":"ok","totalResults":36,"articles":[{"source":{"id":null,"name":"Tmz.com"},"author":"TMZ Staff","title":"'90 Day Fiance' Colt Johnson Files for Divorce from Larissa After Fight and Arrest - TMZ","description":"Colt has filed for divorce from Larissa after the \"90 Day Fiance\" couple's bizarre fight and her arrest.","url":"https://www.tmz.com/2019/01/12/90-day-fiance-colt-johnson-files-divorce-larissa-dos-santos-lima-bloody-fight-arrest/","urlToImage":"https://images.tmz.com/2019/01/12/0112-larissa-johnson-colt-johnson-instagram-01-1200x630.jpg","publishedAt":"2019-01-12T20:55:00Z","content":null},{"source":{"id":null,"name":"Kstp.com"},"author":"The Associated Press","title":"Granddad: Wisconsin girl has no link to suspected kidnapper - KSTP","description":"The grandfather of a northwestern Wisconsin girl who authorities say was abducted during a home invasion that left her parents dead said Saturday that the family has no connection to the suspect and doesn't understand why he targeted her, deepening a mystery …","url":"https://kstp.com/news/granddad-wisconsin-girl-has-no-link-to-suspected-kidnapper-/5207911/","urlToImage":"https://kstp.com/kstpImages/repository/2019-01/800JakeThomasPattersonSuspectNewser2.jpeg","publishedAt":"2019-01-12T20:53:05Z","content":"Jayme had been missing for nearly three months Thursday when she approached a stranger near the small, isolated north woods town of Gordon and pleaded for help. Officers arrested 21-year-old Jake Thomas Patterson minutes later based on Jayme's description of … [+4624 chars]"},{"source":{"id":null,"name":"Vox.com"},"author":"Amanda Sakuma","title":"Megyn Kelly finalizes split with NBC - Vox.com","description":"The talk show host reportedly wanted to be the next Oprah. As she leaves NBC with a record of uncomfortable gaffes, it seems unlikely that will happen.","url":"https://www.vox.com/2019/1/12/18179908/megyn-kelly-nbc-split-oprah","urlToImage":"https://cdn.vox-cdn.com/thumbor/WiGGM5Fmnb_o5PN4zrXsPHnQRx4=/0x215:3000x1786/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/13321989/Kelly.jpg","publishedAt":"2019-01-12T19:57:29Z","content":"Megyn Kelly has officially split with NBC, taking the reminder of her $69 million contract with her, but leaving behind any aspiration of becoming the next queen of talk-show TV. The parties have resolved their differences, and Megyn Kelly is no longer an emp… [+3732 chars]"},
Use json_decode to turn the json you've received into an array!
$result = json_decode($result);
print_r($result);

how can I get the longitude and latitude coordinates of a place using php for geocoding [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to get the longitude and latitude coordinates using php from the given address ($street, $barangay, $city and $province).
You can use url:
http://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ADDRESS
It's free.
You will get data in json encoded form which contain lat & long
Here is an example of PHP code to get the latitude and longitude values from Google Maps API, based on the town, city or country location. Check this tutorial and official documentation.
<?php
$url = "http://maps.google.com/maps/api/geocode/json?address=West+Bridgford&sensor=false&region=UK";
$response = file_get_contents($url);
$response = json_decode($response, true);
//print_r($response);
$lat = $response['results'][0]['geometry']['location']['lat'];
$long = $response['results'][0]['geometry']['location']['lng'];
echo "latitude: " . $lat . " longitude: " . $long;
?>
The http://maps.google.com/maps/api/geocode/json URL have 3 parameters: address (your main location), region and sensor that indicates whether or not the request will come from a device with a location sensor.
You can also check this related SO question. The community suggested to use curl instead of file_get_contents.
$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;
You can use Google Maps Geocoding API, here:
https://developers.google.com/maps/documentation/geocoding/intro
It's free for:
- 2,500 free requests per day
- 10 requests per second
In order to use Google Geocoding API, use this library (MIT license):
http://geocoder-php.org/

How to properly store and lookup areacode from a phone number

How do I store areacodes (npa-nxx) in a database for fast lookup?
Here's the deal: I have a variable that contains a phone number and I need to look in a database for the city attached to that phone number.
The problem is, different countries have different formats.
Canada/USA: +19055551234 (+1 > Country, 905 > Area Code, 555 > City Code)
France: +33512345678 (+33 > Country, 5 > Areacode, 1 > City, Other numbers > Subscriber number)
and so on (infos based on wikipedia)
I created a table called 'npanxx' that contain the list of area codes, city code and city attached to each one (with the id of the country and the province/state id):
CountryId, RegionId, PrimaryCity, npa, nxx, fnpanxx
1 11 Acton Vale 450 236 +1450236
I am thinking about the following procedure:
Get all country codes from sql to php array
Go through each entry and check if there's a match from the beginning of the phone number
When (If there's) a match is found
Remove the beginning of the phone number
Get all npa-nxx that belong to that contry and put them in a php array
Go through each value of the array to find a matching beginning
When (If there's) a match is found
Remove the beginning of the phone number
Store data in different variables like: $country = 'Canada'; $city = 'Acton Vale'...
etc, etc.
First mistake (I think): To much database requests (the npanxx table contain 3000 records for only one province in Canada)
Second mistake: I'm pretty sure there's no need to go through each and every npa-nxx code
another problem: It's not sure that if the phone number is a France one that this procedure will work.
And... If there's an entry for, let's say 336 and another for 3364, it might give the wrong result.
Do you have any idea how I can solve this problem ? (I don't ask for any code, I don't want to to do the work for me, I would like some clues though)
This is for a personnel project to make donation for Multiple Sclerosis Society of Canada and would really like to finish that project :)
I would think maybe some kind of set of reg-exes or other pattern matches to whiddle down your options in terms of search. Just some basic way or "guessing" at the possibilities instead of searching all of them.
Here's a small script I wrote in PHP to return the NPA/NXX as a JSON object in real time from area-codes.com.
It returns some very useful data. It's only for the NANP, so it doesn't do so well trying to discern international calls. For that, I would suggest making a table of all international country codes and the appropriate methods to dial them, internationally.
Additionally, network exchange operators demand an international dial code (like 011 for the USA, or + for cell phones, in general) to figure out if the number is international, and then take the steps, above, to figure out where you're trying to go. You could add this constraint into the input field and be done with it.
If you're trying to just get NPA/NXX information in the North American Numbering Plan, though, this script should be very helpful.
Just an aside, the area-codes.com counts online lookups among their free services, and I have found nothing on the site to suggest that this code violates that policy. But this code can be retooled to gather data from other providers, none-the-less.
<?php
// Small script to return and format all data from the NPA/NXX info site www.area-codes.com
// Returns a JSON object.
error_reporting(E_NONE);
$npa = $_GET['npa'];
$nxx = $_GET['nxx'];
function parseInput($input) {
$v = new DOMDocument();
$v->formatOutput = true;
$v->preserveWhiteSpace = false;
$v->loadHTML($input);
$list = $v->getElementsByTagName("td");
$e = false;
$dataOut = array();
$p = "";
foreach($list as $objNode) {
if (!$e) {
$p = $objNode->nodeValue;
$p = strtolower($p);
$p = preg_replace("%[+ .:()\/_-]%", "", $p);
$p = str_replace("\xc2\xa0", "", $p);
$p = trim($p);
}
else {
if ($p != "") {
$d = trim($objNode->nodeValue);
if ($d != "") $dataOut[$p] = $d;
}
$p = "";
}
$e = !$e;
}
return $dataOut;
}
function getNPANXX($npa, $nxx) {
$url = "www.area-codes.com/exchange/exchange.asp?npa=$npa&nxx=$nxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
$i = strpos($response, "<h3>AreaCode/Prefix $npa-$nxx Details</h3>");
$i = strpos($response, "<table width=\"100%\" border=\"0\" cellpadding=\"2\" cellspacing=\"0\">", $i);
$e = strpos($response, "</table>", $i);
$scan = substr($response, $i, ($e-$i) + 8);
return parseInput($scan);
}
$result = getNPANXX($npa, $nxx);
if (!isset($result['npaareacode'])) {
$result = array("error" => "invalid");
}
echo json_encode($result);
die;
?>
For the query npanxx.php?npa=202&nxx=520 the JSON outputs as follows:
{
"npaareacode":"202",
"nxxusetype":"WIRELESS",
"nxxprefix":"520",
"nxxintroversion":"11\/16\/2007",
"city":"WASHINGTON",
"state":"DC",
"latitude":"38.901",
"county":"DISTRICT OF COLUMBIA",
"longitude":"-77.0315",
"countypopulation":"0",
"lata":"236",
"zipcode":"20005",
"zipcodecount":"0",
"ratecenter":"WSHNGTNZN1",
"zipcodefreq":"0",
"fips":"11001",
"ocn":"6664",
"observesdst":"Unknown",
"cbsacode":"47900",
"timezone":"Eastern (GMT -05:00)",
"cbsaname":"Washington-Arlington-Alexandria, DC-VA-MD-WV",
"carriercompany":"SPRINT SPECTRUM L.P."
}
For your example npanxx.php?npa=450&nxx=236 the data returned is a little bit limited because it's Canada and Canada doesn't provide all the FIPS and carrier data like the United States does, but the returned data still quite useful:
{
"npaareacode":"450",
"nxxusetype":"WIRELESS",
"nxxprefix":"236",
"nxxintroversion":"2002-08-04",
"city":"ACTON VALE",
"state":"QC",
"latitude":"45.6523",
"longitude":"-72.5671",
"countypopulation":"51400",
"lata":"850",
"zipcodecount":"0",
"zipcodefreq":"-1",
"observesdst":"Unknown",
"timezone":"Eastern (GMT -05:00)"
}

Multiple Queries in MQL on Freebase

I am trying to get a list of results from Freebase. I have an array of MIDs. Can someone explain how I would structure the query and pass it to the API in PHP?
I'm new to MQL - I can't even seem to get the example to work:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/writer/film'=>array());
$jsonquerystr = json_encode($simplequery);
// The Freebase API requires a query envelope (which allows you to run multiple queries simultaneously) so we need to wrap our original, simplequery structure in two more arrays before we can pass it to the API:
$queryarray = array('q1'=>array('query'=>$simplequery));
$jsonquerystr = json_encode($queryarray);
// To send the JSON formatted MQL query to the Freebase API use cURL:
#run the query
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
// Decoding the JSON structure back into arrays is performed using json_decode as in:
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an array
// Iterating over the pieces of the resultarray containing films gives us the films Philip K. Dick wrote:
$filmarray = $resultarray["q1"]["result"]["/film/writer/film"];
foreach($filmarray as $film){
print "$film<br>";
}
You're doing everything right. If you weren't, you'd be getting back error messages in your JSON result.
I think what's happened is that the data on Philip K. Dick has been updated to identify him not as the "writer" of films, but as a "film_story_contributor". (He didn't, after all, actually write any of the screenplays.)
Change your simplequery from:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/writer/film'=>array());
To:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/film_story_contributor/film_story_credits'=>array());
You actually can use the Freebase website to drill down into topics to dig up this information, but it's not that easy to find. On the basic Philip K. Dick page (http://www.freebase.com/view/en/philip_k_dick), click the "Edit and Show details" button at the bottom.
The "edit" page (http://www.freebase.com/edit/topic/en/philip_k_dick) shows the Types associated with this topic. The list includes "Film story contributor" but not "writer". Within the Film story contributor block on this page, there's a "detail view" link (http://www.freebase.com/view/en/philip_k_dick/-/film/film_story_contributor/film_story_credits). This is, essentially, what you're trying to replicate with your PHP code.
A similar drill-down on an actual film writer (e.g., Steve Martin), gets you to a property called /film/writer/film (http://www.freebase.com/view/en/steve_martin/-/film/writer/film).
Multiple Queries
You don't say exactly what you're trying to do with an array of MIDs, but firing multiple queries is as simple as adding a q2, q3, etc., all inside the $queryarray. The answers will come back inside the same structure - you can pull them out just like you pull out the q1 data. If you print out your jsonquerystr and jsonresultstr you'll see what's going on.
Modified a bit to include answer into question, as this helped me I've upvoted each, just thought I would provide a more "compleat" answer, as it were:
$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/film_story_contributor/film_story_credits'=>array());
$jsonquerystr = json_encode($simplequery);
// The Freebase API requires a query envelope (which allows you to run multiple queries simultaneously) so we need to wrap our original, simplequery structure in two more arrays before we can pass it to the API:
$queryarray = array('q1'=>array('query'=>$simplequery));
$jsonquerystr = json_encode($queryarray);
// To send the JSON formatted MQL query to the Freebase API use cURL:
#run the query
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
// Decoding the JSON structure back into arrays is performed using json_decode as in:
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an associative array
// Iterating over the pieces of the resultarray containing films gives us the films Philip K. Dick wrote:
if($resultarray['code'] == '/api/status/ok'){
$films = $resultarray['q1']['result']['/film/film_story_contributor/film_story_credits'];
foreach ($films as $film){
print "$film</br>";
}
}

Geographical coordinates to street names

is any way (with a rest API will be awesome) to get the Street name corresponding to a Geographical coordinate? I think the name is geocoding, do google have this API? Im PHP developer.
Ex.
<?php
cor="38.115583,13.37579";
echo(geoname(cor)); // this prints: Foro Umberto I - 90133 Palermo
?>
So the output of the function is the street name, the postal code and the city. Thanks for any help and scripts examples!
Yes, just use the "Reverse Geocoding" function in the Google Maps API: http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding
Here's some example code:
$lat="38.115583";
$long = "13.37579";
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$address = json_decode($curlData);
print_r($address);
Here's my PHP function I used for doing a Reverse Geocode lookup for a street address using the Google MAP API. Note, this example gets the output from Google in JSON, but I am doing a simple parse in PHP.
/*
* Use Google Geocoding API to do a reverse address lookup from GPS coordinates
*/
function GetAddress( $lat, $lng )
{
// Construct the Google Geocode API call
//
$URL = "http://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&sensor=false";
// Extract the location lat and lng values
//
$data = file( $URL );
foreach ($data as $line_num => $line)
{
if ( false != strstr( $line, "\"formatted_address\"" ) )
{
$addr = substr( trim( $line ), 22, -2 );
break;
}
}
return $addr;
}
Andrew
Team at OpenGeoCode.Org
btw> Google does have restrictions on using their APIs for commercial purposes. Basically, you need to display the result on a google map.
You could also take a look at using Yahoo!'s PlaceFinder API, which offers reverse geocoding. A minimal example of a call to the API (asking it to return the lightweight data-interchange format du jour, JSON) might look like:
$url = 'http://where.yahooapis.com/geocode?location=55.948496,-3.198909&gflags=R&flags=J';
$response = json_decode(file_get_contents($url));
$location = $response->ResultSet->Results[0];
print_r($location);
Which outputs the first result (hopefully there is one!) which contains properties like street, postal and city.
Another way of using the PlaceFinder API is through Yahoo!'s YQL API, which allows you to make use of SQL-like queries against "data tables" (often, other APIs).
Such a query might look like:
SELECT * FROM geo.placefinder WHERE text="55.948496,-3.198909" AND gflags="R"
(Try this in the YQL console interface)
To make a call to YQL with that query, from PHP, is very similar to the earlier example and should print the same information.
$query = 'SELECT * FROM geo.placefinder WHERE text="55.948496,-3.198909" AND gflags="R"';
$url = 'http://query.yahooapis.com/v1/public/yql?q='.urlencode($query).'&format=json';
$response = json_decode(file_get_contents($url));
$location = $response->query->results->Result;
print_r($location);
As #Elijah mentions, there's a lot of restrictions on the Maps API I gave in my last answer. You're only actually supposed to use it for Google Maps Applications. If that's a problem then you can also try the AdWords API. It also has a similar service but Google charges for it so there's less restriction.

Categories