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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With