Search code examples
phpapiopenstreetmap

How can I access OpenStreetMap API data using PHP?


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.


Solution

  • 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;