【问题标题】:Trying to return lat and long from Google Geocode尝试从 Google Geocode 返回 lat 和 long
【发布时间】:2012-05-01 20:13:12
【问题描述】:

这是我第一次使用 JSON,我显然遇到了一些问题,我只是非常不确定它是什么。

我已经查找了如何解析简单的 json,但我认为它可能会让我失望。

这就是我试图获得我的价值观的方式:

$getJSON = "http://maps.googleapis.com/maps/api/geocode/json?address=" . str_replace(" ", "", $_POST['postcode']) . "&sensor=false";
            $contentJSON = file_get_contents($getJSON);
            $Geocode_array = json_decode($contentJSON, true);

            $lat = $Geocode_array[results][address_components][geometry][location][lat];
            $lng = $Geocode_array[results][address_components][geometry][location][lng];

如果需要,我可以发布 json 代码。

【问题讨论】:

    标签: php json parsing google-geocoder


    【解决方案1】:

    尝试引用您的数组键。如果没有引号,PHP 会假设这些键是未定义的常量。此外,您还没有完全正确地遍历 JSON 结果。试试这个:

    $lat = $Geocode_array['results'][0]['geometry']['location']['lat'];
    $lng = $Geocode_array['results'][0]['geometry']['location']['lng'];
    

    Google Maps API 在一个数组中为您提供多个结果。我在上面的代码中引用了第一个(索引0)。在开发过程中要做的一件有用的事情是使用print_r() 将关联数组打印到 PHP 输出缓冲区。我就是这么想的。

    print_r($Geocode_array);
    

    【讨论】:

    • 这并没有什么不同,我是不是在挖掘 JSON 级别错误?
    • 您可能有多个问题。让我做一些测试,我会让你知道我发现了什么......
    • 谢谢,非常感谢您的帮助
    • @Toadfish 我已经更新了我的答案。我想我也发现了你的其他问题。
    • 工作出色!我不知道 print_r() 函数,但现在我知道未来了。感谢 Asaph 的超快速解决方案!
    猜你喜欢
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2020-05-30
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多