【问题标题】:fetch latitude, longitude of multiple addresses php code获取多个地址的经纬度php代码
【发布时间】:2013-09-15 08:48:14
【问题描述】:

我的数据库中保存了多个地址。我想获取多个地址的经度和纬度。 我正在使用代码:

foreach($address as $addr)
{
      $prepAddr = str_replace(' ','+',$addr);
      $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
      $output= json_decode($geocode);
      echo   $latitude = $output->results[0]->geometry->location->lat;
      echo   $longitude = $output->results[0]->geometry->location->lng;
}

$address 是返回所有地址的数组。

问题是由于地址在 500 以上,所以页面加载时间很长。 我参考了链接How to get longitude latitude of multiple addresses geo-location

但是,不能让它工作。

请你帮帮我。非常感谢任何帮助。

【问题讨论】:

标签: php google-maps google-maps-api-3


【解决方案1】:

首先使用 foreach 而不是 for 循环,因为它更快。

第二件事是使用 CURL 而不是 file_get_content 因为 curl 比我在 SO 的讨论中看到的更快。

查看此链接:using file get contents or curl

你可以使用 curl 这里是 curl 的示例代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, trim($request)); 
$result = curl_exec($ch);
curl_close($ch);

这肯定会减少执行时间。

【讨论】:

    【解决方案2】:

    我建议延迟更多地与连接到 api 并取回数据所需的时间有关,而不是循环本身的速度。

    为了使其更具可扩展性,您不妨看看它可以处理多少个地址,然后分批处理它们。如果 100 可以正常工作,则使用 start=100 加载它,并在运行结束时,让脚本再次使用 start=$start+100 调用自身,直到没有剩余。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 2012-09-30
      • 2013-07-04
      • 2014-06-14
      • 1970-01-01
      相关资源
      最近更新 更多