【问题标题】:Using Geolocation in PHP在 PHP 中使用地理定位
【发布时间】:2015-10-26 05:39:32
【问题描述】:

我有一个 PHP 页面,其中包含以下代码,用于从用户输入的邮政编码中获取纬度和经度。

但是当我尝试运行它时,我收到以下错误:

警告:file_get_contents(): https:// 包装器在 通过 allow_url_fopen=0 配置服务器 /home/metsrobo/public_html/PHPPage2.php 在第 4 行

警告: 文件获取内容(https://maps.googleapis.com/maps/api/geocode/json?address=750341&sensor=false&key=AIzaSyDa3Jhr3c5x_2GWrPwRoMWDXrMSYl3KvOA): 无法打开流:在第 4 行找不到合适的包装器。

<?php
    function getLnt($zip){
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false&key=AIzaSyDa3Jhr3c5x_2GWrPwRoMWDXrMSYl3KvOA";
    $result_string = file_get_contents($url);
    $result = json_decode($result_string, true);
    return $result['results'][0]['geometry']['location'];
    }
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <?php
         $val = getLnt('750341');
         echo "Latitude: ".$val['lat']."<br>";
         echo "Longitude: ".$val['lng']."<br>";
        ?>
    </body>
</html>

【问题讨论】:

  • 我不确定您是否将 API 密钥限制为可以通过域或 ip 或其他方式访问,我尝试单击链接,但访问被拒绝。
  • 请问我在创建 api 时应该设置哪些设置?
  • prntscr.com/8venng我这样设置,效果很好。

标签: php api geolocation


【解决方案1】:

不要将 api 密钥与 url 一起使用,删除 api 密钥然后它会起作用,因为要获取纬度和经度,您不需要 api 密钥。如下更改网址

https://maps.googleapis.com/maps/api/geocode/json?address=750341&sensor=false

【讨论】:

    【解决方案2】:

    要使file_get_contents() 功能起作用,首先您需要启用allow_url_fopen 并将其值设置为On。

    同样,你可以尝试两件事。

    1. 创建一个.htaccess 文件并将其保存在根文件夹中(有时可能需要将其放置在根目录的后退文件夹中)并将此代码粘贴到那里。

      php_value allow_url_fopen On
      
    2. 创建一个php.ini 文件(用于更新服务器php5.ini)并将其保存在根文件夹中(有时可能需要将其放置在根目录的上一步)并将以下代码粘贴到那里:

      allow_url_fopen = On;
      

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-14
      • 2012-01-03
      • 1970-01-01
      • 2012-01-04
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多