简体   繁体   中英

Can get JSON from Google Maps call

I have managed to get the longitude and latitude of postcodes from Google Maps but I am unable to then get the distance between the two. The following url gives me some JSON:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=51.6896118,-0.7846495&destinations=51.7651382,-3.7914676&units=imperial&sensor=false

But I can't strip it out using PHP:

<?php
    $du = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=51.6896118,-0.7846495&destinations=51.7651382,-3.7914676&units=imperial&sensor=false";
    $djd = json_decode(utf8_encode($du),true);
    print("-".$djd."-");
?>

Anybody know why this is?

EDIT

The following worked just fine:

<?php
    $pc1 = 'SA92NH';
    $pc2 = 'HP270SW';
    $url1 = "https://maps.googleapis.com/maps/api/geocode/json?address=".$pc1."&sensor=false";
    $url2 = "https://maps.googleapis.com/maps/api/geocode/json?address=".$pc2."&sensor=false";
    $url1_data = file_get_contents($url1);
    $url2_data = file_get_contents($url2);
    $json1_data = json_decode(utf8_encode($url1_data),true);
    $json2_data = json_decode(utf8_encode($url2_data),true);
    $longlat1 = $json1_data['results'][0]['geometry']['location']['lat'].",".$json1_data['results'][0]['geometry']['location']['lng'];
    $longlat2 = $json2_data['results'][0]['geometry']['location']['lat'].",".$json2_data['results'][0]['geometry']['location']['lng'];
    print($longlat1."<br>\n");
    print($longlat2."<br>\n");
?>

Is this what you are looking for? You need to get the data, you cannot only type the url.

In my example i use get file_get_contents .

<?php
    $du = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?origins=51.6896118,-0.7846495&destinations=51.7651382,-3.7914676&units=imperial&sensor=false");
    $djd = json_decode(utf8_encode($du),true);
    print_r($djd);
?>

http://codepad.viper-7.com/LqxpJW

$url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=51.6896118,-0.7846495&destinations=51.7651382,-3.7914676&units=imperial&sensor=false';

$content = file_get_contents($url);
$json = json_decode($content, true);

And after that access $json like an array ! Something like that:

echo $json['rows']['elements']['distance']['text'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM