I'm trying to get the latitude and longitude from google maps API, I'm also using a PHP RESTful API that I've been developing, but I can not get/print the array with the values, am I doing correctly?
I've already tried it using the postman app, to see if I'm getting something, but it gave the 200 status and it doesn´t show anything. This is the way i'm doing the call:
https://skeleton-app-itson.000webhostapp.com/rest/index.php/Prueba/latLong/Mexico
This is problem
function latLong_get($address){
if(!empty($address)){
//Formatted 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&key=IALREADYHAVETHEKEY');
$output = json_decode($geocodeFromAddr);
//Get latitude and longitute from json data
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longitude'] = $output->results[0]->geometry->location->lng;
//Return latitude and longitude of the given address
if(!empty($data)){
echo $data;
}else{
return false;
}
}else{
return false;
}
}
I'm expecting an array with the values, but I've been getting an empty screen
You try to print an array - this is error. For example, you can try
if(!empty($data)){
echo json_encode($data);
}
Related
I have a pho script that takes an address and returns the lat/lon. Works fine until I put the google api key at the end of the url. I tested the url in the browser and it works fine there.
This works fine:
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
This causes an error:
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'+&sensor=false+CA&key=[MyAPIKeyHere]');
It causes the error: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
I've seen consulted similar posts such as,
Warning while using file_get_contents for google api , but they weren't much help.
Here is the complete code:
<?php
// Address
$address = '1451 Broadway New York, NY 10036';
// Address from command line
// $address = readline("Enter an address: ");
// $address = str_replace(' ','+',$address);
// Get JSON results from this request
// This url works
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
// This url creates an error
//$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'+&sensor=false+CA&key=[MyAPIKeyHere]');
// Convert the JSON to an array
$geo = json_decode($geo, true);
if ($geo['status'] == 'OK') {
// Get Lat & Long
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}
// $address = str_replace('+',' ',$address);
echo "The address ". $address. " has the following coordinates:\n" ;
echo "Lat: ". $latitude. " Lon: ". $longitude. "\n";
?>
Try using this API. It worked for me.
https://maps.googleapis.com/maps/api/geocode/json?address='.$address.'&key=YOUR_API_KEY'
I am writing API's in PHP for the ios developer for that I am writing the API that receives the array of items in API firstly I am unable to send the JSON data.
But I get the response that is not valid you can view the image below.
So how can I send the JSON array data and get the response? I had developed many apis by sending one key value pair that works fine but not knows how to send the array of items. Here is the code in am try to get the values.
require_once('db/db_config.php');
$enable_log = 0;
if ($enable_log) {
$data = ' GET DATA ' . print_r($_GET, 1);
$data = ' GET DATA ' . print_r($_FILES, 1);
$data .= ' POST DATA ' . print_r($_POST, 1);
$time = #date('[d/M/Y:H:i:s]');
error_log($time . $data . PHP_EOL, 3, "login.log");
}
//call to helper function
$app_type = request_check();
$token = isset($_REQUEST['token']) ? $_REQUEST['token'] : '';
$employee_id = isset($_REQUEST['employee_id']) ? $_REQUEST['employee_id'] : '';
$order_item_array = isset($_REQUEST['ordered_items']) ? $_REQUEST['ordered_items'] : '';
$decode = (array) json_decode($_REQUEST['ordered_items'], true);
echo "<pre>";print_r($decode);exit;
Thanks in advance.
convert your data into Json and than base 64 and call the url using post you can send a lot of data converting into Json
I'm uploading a csv file and getting address field in $address variable, but when I pass $address to google maps, its showing me error,
file_get_contents(http://maps.googleapis.com/maps/api/geocode/json?address=9340+Middle+River+Street%A0%2COxford%2CMS%2C38655): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request.
I searched for its solution, I found one that to encode only address but its also not working for me...
CODE
if (!empty($address)) {
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address));
$geo = json_decode($geo, true);
if ($geo['status'] = 'OK') {
if (!empty($geo['results'][0])) {
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}
$mapdata['latitude'] = $latitude;
$mapdata['longitude'] = $longitude;
return $mapdata;
} else {
$mapdata['latitude'] = "";
$mapdata['longitude'] = "";
return $mapdata;
}
}
Error is at line
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address));
Have I missed anything.!
Any help is much appreciated.. Thanks
you need to use google api key
function getLatLong($address){
if(!empty($address)){
//Formatted 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
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longitude'] = $output->results[0]->geometry->location->lng;
//Return latitude and longitude of the given address
if(!empty($data)){
return $data;
}else{
return false;
}
}else{
return false;
}
}
Use getLatLong() function like the following.
$address = 'White House, Pennsylvania Avenue Northwest, Washington, DC, United States';
$latLong = getLatLong($address);
$latitude = $latLong['latitude']?$latLong['latitude']:'Not found';
$longitude = $latLong['longitude']?$latLong['longitude']:'Not found';
To specify a Google API key in your request, include it as the value of a key parameter.
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=true_or_false&key=GoogleAPIKey');
i hope this will help you.
It looks like the problem is with your data set. The part of the url that is being encoded as %A0 by urlencode($address) is a special non-breaking space character, rather than a regular space.
See here for more information on the difference:
Difference between "+" and "%A0" - urlencoding?
The %A0 character isn't accepted in this context, but you can do a quick str_replace() on the result of urlencode() to replace all these special space characters with the + symbols that regular spaces would have resulted in.
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . str_replace('%A0', '+', urlencode($address)));
Currently using downloadURL() on home.php that downloads an xml.php file. Creates xml doc from database to display markers on map. Worked fine earlier, but now I'm receiving errors around geoCode/lat/long. Any advice? FireFox error: undefined offset [0] via results.
<?php
include 'connect.php';
if(isset($_SESSION['user_name']))
{
header('Location: home.php');
}
$query = "SELECT `acc_id`,`acc_name`,`acc_address`,acc_zip FROM `account_acc` ";
$result = mysqli_query($connection,$query) or die(mysql_error());
$doc = new DomDocument('1.0');
$node = $doc->createElement("markers");
$parnode = $doc->appendChild($node);
header('Content-type: text/xml');
while($row = mysqli_fetch_array($result))
{
$node = $doc->createElement("marker");
$newnode = $parnode->appendChild($node);
$address = $row['acc_zip'];
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?key=API&address='.$prepAddr);
$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
$newnode->setAttribute("name", $row['acc_name']);
$newnode->setAttribute("accid", $row['acc_id']);
$newnode->setAttribute("address", $row['acc_address']);
$newnode->setAttribute("zip", $row['acc_zip']);
$newnode->setAttribute("lat", $lat);
$newnode->setAttribute("long", $long);
}
print $doc->saveXML();
?>
There aren't lat/lng properties of location, they are functions (lat()/lng()).
Most likely you are getting the error undefined offset [0] since the provided address ($address variable) could not be determined and the response contains empty results. For that case Google Maps Geocoding API provides Status Codes:
"OK" indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned.
"ZERO_RESULTS" indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a
non-existent address.
"OVER_QUERY_LIMIT" indicates that you are over your quota.
"REQUEST_DENIED" indicates that your request was denied.
"INVALID_REQUEST" generally indicates that the query (address, components or latlng) is missing.
"UNKNOWN_ERROR" indicates that the request could not be processed due to a server error. The request may succeed if you try again.
that you could utilize to determine whether address has been resolved.
Example
$geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address=' . $prepAddr);
$output = json_decode($geocode);
if($output->status == "OK"){
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
//the remaining code goes here...
}
I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.