I am trying to access OpenStreetMap data using PHP, but I cannot find any clear answers on how to do so. The URL I am trying to pull data from works when I search it in the browser.
Here is the URL I am trying: https://nominatim.openstreetmap.org/search?q=jacksonville,florida&format=json
And this is how I am trying to access it in my PHP file, but it always returns nothing.
$search_url = "https://nominatim.openstreetmap.org/search?q=jacksonville,florida&format=json";
$json = file_get_contents($search_url);
print_r($json);
echo "json=" . $json;
$decoded = json_decode($json, true);
$lat = $decoded[0]["lat"];
$lng = $decoded[0]["lon"];
echo " latitude=".$lat . " -----" . "longitude=".$lng;
How can I fix this? My end goal is to simply get the latitude and longitude of a city, state.
I suspect that the api is refusing to serve a request without a valid User-Agent and http referrer header, try setting this and it should work, for example:
<?php
$search_url = "https://nominatim.openstreetmap.org/search?q=jacksonville,florida&format=json";
$httpOptions = [
"http" => [
"method" => "GET",
"header" => "User-Agent: Nominatim-Test"
]
];
$streamContext = stream_context_create($httpOptions);
$json = file_get_contents($search_url, false, $streamContext);
print_r($json);
echo "json=" . $json;
$decoded = json_decode($json, true);
$lat = $decoded[0]["lat"];
$lng = $decoded[0]["lon"];
echo " latitude=".$lat . " -----" . "longitude=".$lng;
Related
I am trying to update data in API using Guzzle. And during running I meet this Failed to decode json error. Below is what I've done:
$client = new Client([
'headers' => [
'Authorization' => 'Bearer ' . env('API_TOKEN'),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
$api_link = env('KINGTIME_API');
$updateAPIlink = $api_link . 'daily-schedules/' . $emp_key . '/' . $date;
$response = $client->put(
$updateAPIlink,
json_decode(json_encode(['form_data' => $tobeUpdated])
), true);
The above code returns the Failed to decode JSON error and data inside my $tobeUpdated variable is like this:
array(8) {
["workPlaceDivisionCode"]=>
string(7) "testeam"
["clockInSchedule"]=>
string(0) "2019-01-01T19:00+09:00"
["clockOutSchedule"]=>
string(0) "2019-01-01T19:00+09:00"
["workFixedStart"]=>
string(22) "2019-01-01T08:00+09:00"
["workFixedEnd"]=>
string(22) "2019-01-01T19:00+09:00"
}
When I try to test in Postman, it receives data in like this formnat:
{
"workPlaceDivisionCode": "testeam",
"clockInSchedule": "2019-01-01T09:00+09:00",
"clockOutSchedule": "2019-01-01T18:00+09:00",
"workFixedStart": "2019-01-01T08:00+09:00",
"workFixedEnd": "2019-01-01T19:00+09:00"
}
Is the error from the API itself or from my data feed? If on my data feed, how can I make a date like the format to feed using Postman? This is my first time to work on API.
I think your going about this the wrong way:
Try simplifying this section of your code:
$response = $client->put(
$updateAPIlink,
json_decode(json_encode(['form_data' => $tobeUpdated])
), true); //<--Was this "true" suppose to be part of your json_decode or a value to be added to the client?
To this:
$response = $client->put(
$updateAPIlink,
array(
'form_data' => $tobeUpdated
)
);
The data that you are getting from Postman is in the JSON format. You need to convert the JSON string to an object or array and then you will be able to access your values.
Like so:
echo '<pre>';
$json = ' {
"workPlaceDivisionCode": "testeam",
"clockInSchedule": "2019-01-01T09:00+09:00",
"clockOutSchedule": "2019-01-01T18:00+09:00",
"workFixedStart": "2019-01-01T08:00+09:00",
"workFixedEnd": "2019-01-01T19:00+09:00"
}';
//To get the data as an object:
$object = json_decode($json);
var_dump($object);
echo '<br>';
echo $object->clockInSchedule . '<br><br>';
//To get the data as an array us the "TRUE" flag:
$array = json_decode($json, true);
var_dump($array);
echo '<br>';
echo $array['clockInSchedule'] .'<br><br>';
echo '</pre>';
Let me know if it helps.
I am developing an android app where I have to get the user's speed and match it with the speedlimit of the road in order to see how he/she is driving.
I am using Open Street Maps to get the road speed limit. But, I'm having problem in getting the tag 'max-speedlimit' which gives the speed limit of the road. Below given php code I am using to get the latitude and longitude from the app and then finding the speed limit. I am having hardtime getting the speedlimit. As there are so many tags in the response from the OSM, I only want to get the max-speed tag's value
Thank you so much!
<?php
$lat = isset($_POST['lat']) ? floatval($_POST['lat']) : "";
$lng = isset($_POST['lng']) ? floatval($_POST['lng']) : "";
$latm = -0.00015 + $lat;
$latp = 0.00015 + $lat;
$lngm = -0.00015 + $lng;
$lngp = 0.00015 + $lng;
$json_url = 'http://overpass.osm.rambler.ru/cgi/interpreter';
$data = '<query type="way"> <bbox-query s="' . $lngm . '" w="' . $latm . '" n="' . $lngp . '" e="' . $latp . '"/> <!--this is auto-completed with the current map view coordinates.--> </query> <print/>';
$ch = curl_init( $json_url );
$options = array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch);
//CONVERT THE RESPONSE IN STRING AND GET THE MAXSPEED TAG VALUE ONLY!
I am trying to get the speed limit using the OSM through php. But, I am unable to do that because I am getting the message as written below:
The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.
What could be the problem? Below is my php file.
Note: the code is still incomplete, I'm for now testing if I am able to access the OSM database.. But I cant. I hope someone could point me to the right direction..
<?php
$lat = 24.32633;
$lng = 54.58061;
$latm = -0.00015 + $lat;
$latp = 0.00015 + $lat;
$lngm = -0.00015 + $lng;
$lngp = 0.00015 + $lng;
//$json_url = 'http://overpass-api.de/api/interpreter?data=[out:json];node(24.326180, 54.580460,24.336580, 54.580860);way(bn);(._;>;);out;';
$json_url = 'http://overpass.osm.rambler.ru/cgi/interpreter';
$data = '<query type="way"> <bbox-query s="' . $lngm . '" w="' . $latm . '" n="' . $lngp . '" e="' . $latp . '"/> <!--this is auto-completed with the current map view coordinates.--> </query> <print/>';
$ch = curl_init( $json_url );
$options = array(
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch);
echo curl_exec($ch);
/*$resultArr = explode("<",$result);
foreach ($resultArr as $val) {
$temp = explode('"', $val);
//check the size of the array, if it is == 5, then do
if ($temp[1]=="maxspeed")
$speedlimit=$temp[3];
}
echo '{"speedlimit": "120"}'; */
?>
Your bounding box is quite small and there's simply no data available in OpenStreetMap for your bounding box. That why you get the following almost empty, but valid result:
<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="Overpass API">
<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
<meta osm_base="2015-06-06T08:10:03Z"/>
<bounds minlat="54.5805" minlon="24.3262" maxlat="54.5808" maxlon="24.3265"/>
</osm>
I would highly recommend to try different options in overpass turbo first to get more familiar with Overpass API. Please check the following link as a starting point: http://overpass-turbo.eu/s/9MQ - it's also restricted to highways with a maxspeed tag (that's what you're looking for, right?).
For illustration purposes, here's a screenshot with your tiny bounding box in the middle:
Hello everyone I am a newbie to php and this is my first ever app over php.
I am trying to create a new album through graph api and upload photos to it.
I’ve the following code in place, problem is when after creating an album facebook graph api returns data that contains the id of the album and that id is later used to upload photos to that album.
In my case I am getting the data but I am unable to read through it, I tried to access it as an object, as an array but none is working.
To check the viability when I tried to print it whole it is giving output like this.
Result: {"data":[{"id":"321215475937088","from":{"name":"Lorem …
I want to know how I can access this id element? whether $result is an array, object or what. I’ve tried every possibility that I could come up with but am not getting the required output.
// Create a new album
$graph_url = "https://graph.facebook.com/me/albums?" . "access_token=" . $access_token;
$postdata = http_build_query(array('name' => $album_name, 'message' => $album_description));
$opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
$context = stream_context_create($opts);
//$result = json_decode(file_get_contents($graph_url, false, $context));
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
echo "<pre>";
echo "Result: " . $result; //output of this line is given above
echo "Result[id]: " . $result[id]; //Notice: Use of undefined constant id - assumed 'id' ...
echo "Result[data][id]: " . $result[data][id]; //Notice: Use of undefined constant data - assumed 'data'...
//Notice: Use of undefined constant id - assumed 'id'...
//Fatal error: Cannot use string offset as an array in ...
echo "Result ID: " . $result -> id;
echo "Data - >ID: " . $data->id;
echo "Data ID: " . $data[id];
echo "</pre>";
// Get the new album ID
$album_id = $result -> id;
You're getting JSON serialized object.
You need to deserialize it before use.
You could do it like this:
echo "Result: " . $result;
$result = json_decode($result);
After that you can access properties of the object:
echo "Result ID: " . $result->data[0]->id;
*Please note that data in your response string is an array which contains objects
Its JSON format. You can convert it to array/object with json_decode();
$json_data = json_decode($responce_string);
Read the manual for more information
Use json_decode on the response to deserialize the JSON string received.
Response from Graph API are JSON serialized.
Use json_decode to deserialize 'em
print_r(json_decode($result));
BTW, use Facebook PHP SDK and save yourself time and code ;)
curl -i -X POST -d 'json={"Amount":1000,"idPlayers":1}' http://www.myurl.com/updateamount.php
My php code:
<?php
$json = urldecode($_GET['jsonSendData']);
$json = str_replace("\\", "", $json);
$data = json_decode($json, true);
// if i hard code it here it works fine, but need from a post from curl
//$json = '{"Amount":1000,"idPlayers":1}';
$data = json_decode($json, true);
echo "json = ", $json;
$amount = mysql_real_escape_string($data['Amount']);
$id = mysql_real_escape_string($data['idPlayers']);
echo "Amount = ",$amount;
return;
Try to change to read post data and using the correct name:
$json = urldecode($_POST['json']);