Using PHP (curl) to pull data from JSON (Google Maps API)

后端 未结 2 1404
清酒与你
清酒与你 2020-12-23 17:31

I\'m fairly new to JSON, and I\'m trying to get the latitude and longitude of a geocoded city from the Google Maps API using curl. The function I\'m using is:



        
相关标签:
2条回答
  • 2020-12-23 18:11

    Note that it seems that results contains an array (with only one item in it, here) of results ; and geometry is one item inside one result.

    Here, you can see that results' content is delimited by [] -- which indicates it's an array.


    So, you have to first access the first result : $geoloc['results'][0]
    Inside of which you'll have the geometry : $geoloc['results'][0]['geometry']

    Which will allow you to get the latitude and longitude :

    var_dump($geoloc['results'][0]['geometry']['location']['lat']);
    var_dump($geoloc['results'][0]['geometry']['location']['lng']);
    


    I suppose that, depending on the address you've searched on, you will sometimes have more than one item in the results array.

    0 讨论(0)
  • 2020-12-23 18:21

    You just need this :

    $fullurl = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
    $string .= file_get_contents($fullurl); // get json content
    $json_a = json_decode($string, true); //json decoder
    
    echo $json_a['results'][0]['geometry']['location']['lat']; // get lat for json
    echo $json_a['results'][0]['geometry']['location']['lng']; // get ing for json
    
    0 讨论(0)
提交回复
热议问题