Convert Address to Latitude/longitude (using php) - php

I want to parse this URL with PHP to get the latitude of a specific address (2+bis+avenue+Foch75116+Paris+FR):
I use the google maps web service: http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
var_dump($obj);
It doesn't work. I have this error :
OVER_QUERY_LIMIT
So I searched on the web and I found that there is a limitation using google maps api (Min 1 sec between 2 queries and max 2500 queries per day)
Do you know any way to convert an adress to --> Latitude/Longitude ???

You are accessing results incorrectly.
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;

Related

My code for downloading longitude and latitude is now returning null value for existing areas

I have a code for downloading longitude and latitude coordinates from google maps, it was working before but now it's returning null value. Below is my code;
<?php
//Optaining Latitude and Longitude
$address = $title;
$url = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&sensor=false");
$response = json_decode($url);
$latitudee = "";
$longitudee = "";
if ($response->status == 'OK') {
$latitudee = $response->results[0]->geometry->location->lat;
$longitudee = $response->results[0]->geometry->location->lng;
}
echo $latitudee;
?>
Google now requires you to include API key for calling geocode API. Change the 'url' variable as follows-
$url = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&key=YOUR_API_KEY");
The sensor parameter is no longer required to pass as per google developer guide
https://developers.google.com/maps/documentation/geocoding/intro
If you don't have an API key, you can get it here-
https://developers.google.com/maps/documentation/javascript/get-api-key
Also don't forget to restrict your key once you have one.
Returned error message states what is the problem here:
Keyless access to Google Maps Platform is deprecated.
Please use an API key with all your API calls to avoid service interruption.
For further details please refer to http://g.co/dev/maps-no-account
After recent changes to google maps, you will need to create an account to use google maps API, this will generate an API key and you have to append it to URL that you use
"http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&key=YOUR_API_KEY"
you must Formatted your address:
$formattedAddr = str_replace(' ','+',$address);
Send request and receive json data by address:
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false');
$output = json_decode($geocodeFromAddr);
Get latitude and longitute from json data:
if ($output->status == 'OK') {
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longitude'] = $output->results[0]->geometry->location->lng;
}
I was able to find where the problem was, Google changed the API url to the one below;
$url = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($add`enter code here`ress)."&key=YOUR_API_KEY");

How to use Nominatim API through PHP to retrieve latitude and longitude?

Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.

How to get video duration using YouTube API? [duplicate]

This question already has answers here:
How do I get video durations with YouTube API version 3?
(7 answers)
Closed 4 years ago.
I want to get the duration of a Youtube video. Here's the code I tried:
$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
Please check the XML file. I got the title of this video. I want to get duration from <yt:duration seconds='29'/>.
How to get the seconds attribute this <yt> tag?
Due to the upcoming deprecation of the YouTube v2 API, here is an updated solution.
Start by cloning the Google API PHP Client here
Next, you'll want to register an application with Google here by creating a new Project, turning on the YouTube Data API under the "APIs and auth → API" section, and
Create a new OAuth Client ID under "APIs and auth → Credentials" and add the full path to your redirect URI list. (i.e. http://example.com/get_youtube_duration.php)
Use this code (which was adapted from this sample code), while making sure to fill in the $OAUTH2_CLIENT_ID and $OAUTH2_CLIENT_SECRET variables with your own values from step 3.
Hardcode a value for the $videoId variable or set it using the video_id get parameter (i.e. http://example.com/get_youtube_duration.php?video_id=XXXXXXX)
Visit your script, click the link to authorize the app and use your google account to get a token, which redirects you back to your code and will display the duration.
Here is your output:
Video Duration
0 mins
29 secs
Some additional resources:
https://developers.google.com/youtube/v3/docs/videos#contentDetails.duration
https://developers.google.com/youtube/v3/docs/videos/list
The following works for the V2 API only.
This worked for me based on the assumption that there is only one duration element in the feed.
<?php
$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$duration = $doc->getElementsByTagName('duration')->item(0)->getAttribute('seconds');
print "TITLE: ".$title."<br />";
print "Duration: ".$duration ."<br />";
Output:
TITLE: Introducing iTime
Duration: 29
Here it is YouTube API V3, with example of getting video duration, but do not forget to create your API key at https://console.developers.google.com/project
$vidkey = "cHPMH2sa2Q" ; video key for example
$apikey = "xxxxxxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
A short and simple solution using SimpleXML:
function getYouTubeVideoDuration($id) {
$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos/'.$id);
return strval($xml->xpath('//yt:duration[#seconds]')[0]->attributes()->seconds);
}
All the prev answers provide the duration in a text format:
This solution will give you the hours / minutes / seconds for you to transform to whatever format you would like:
function getDurationInSeconds($talkId){
$vidkey = $talkId;
$apikey = "xxxxx";
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
preg_match_all('/(\d+)/', $VidDuration, $parts);
$hours = intval(floor($parts[0][0]/60) * 60 * 60);
$minutes = intval($parts[0][0]%60 * 60);
$seconds = intval($parts[0][1]);
$totalSec = $hours + $minutes + $seconds; // This is the example in seconds
return $totalSec;
}
Very easy
function getYoutubeDuration($videoid) {
$xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
$result = $xml->xpath('//yt:duration[#seconds]');
$total_seconds = (int) $result[0]->attributes()->seconds;
return $total_seconds;
}
//now call this pretty function. As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");
You can also get the duration in JSON
$video_id = "<VIDEO_ID>";
http://gdata.youtube.com/feeds/api/videos/$video_id?v=2&alt=jsonc
Oh! Sorry you can get it by:
$duration = $xml->getElementsByTagName('duration')->item(0)->getAttribute('seconds');

Google Maps API with PHP to find distance between two locations

On my current project, which is a delivery system, I have a list of available delivery drivers, which is shown on an orders page. But what I need is to show the distance each delivery is from the customers address. The distance should be shown next to each driver's name. Anyone have any clues on how I would go about this?
Assuming that you want driving distance and not straight line distance, you can use the Directions web service:
You need to make an http or https request from your PHP script and the parse the JSON or XML response.
Documentation:
https://developers.google.com/maps/documentation/directions/
For example:
Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (JSON)
http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false
Boston,MA to Concord,MA via Charlestown,MA and Lexington,MA (XML)
http://maps.googleapis.com/maps/api/directions/xml?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&sensor=false
Note that there are usage limits.
You can easily calculates the distance between two address using Google Maps API and PHP.
$addressFrom = 'Insert from address';
$addressTo = 'Insert to address';
$distance = getDistance($addressFrom, $addressTo, "K");
echo $distance;
You can get the getDistance() function codes from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/
this will out seconds between 2 location
$origin =urlencode('Optus Sydney International Airport, Airport Drive, Mascot NSW 2020, Australia');
$destination = urlencode('Sydney NSW, Australia');
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$origin&destinations=$destination&key=your_key";
$data = #file_get_contents($url);
$data = json_decode($data,true);
echo $data['rows'][0]['elements'][0]['duration']['value'];

PHP & API for IP Geolocation

I am trying to use http://www.hostip.info/use.html in my web app to show the approximate City location of an IP address. I cannot figure out how to actually show the contents of the API... Here is what I have that is not working.
function showCity($currIP){
$lookupData = 'http://api.hostip.info/get_html.php?ip='.$currIP;
return $lookupData;
}
Your API returns this:
Country: UNITED STATES (US)
City: Seattle, WA
IP: 168.111.127.225
So you need to do some string parsing on that result. Using the below will get your started:
$array = preg_split('/$\R?^:/m', $lookupData);
print_r($array);
Try this instead:
$array = preg_split("/[\r\n]/", $lookupData, -1, PREG_SPLIT_NO_EMPTY);
Also, as was mentioned by mcmajkel, if you use the JSON api link, you can get to it with this:
$lookupData = 'http://api.hostip.info/get_json.php?ip='.$currIP;
$api = json_decode($lookupData);
$myName = $api->country_name;
$myCode = $api->country_code;
$myCity = $api->city;
$myIP = $api->ip;
This call returns string, as mentioned by GregP. But you can call
http://api.hostip.info/get_json.php?ip=12.215.42.19
And get a nice piece of JSON in return, which will be easier to
parse

Categories