【问题标题】:how to get distance from two locations name using php如何使用php从两个位置名称获取距离
【发布时间】:2017-01-24 11:55:42
【问题描述】:

我的 php 代码使用位置编号返回 $distance 值,但如何使用位置名称获取距离? 这里代码

$from = "Arlington Heights, IL 60005, United States";
$to = 'Arlington Heights, IL 60004, United States';
$from = urlencode($from);
$to = urlencode($to);
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);
$time = 0;
$distance = 0;

foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}   

【问题讨论】:

  • “位置编号”是什么意思?据我所知,您在代码中使用了实际的地名?

标签: php location


【解决方案1】:

好的,看来我对逗号的理解是错误的,但请注意此查询不需要它们,并且可能会导致错误,尤其是在您依赖用户输入的情况下。我相信您的问题归结于您的 foreach() 循环,因为如果您只是查询 AB,那么它并不是真正需要的。此外,您查询数组就像它不是一个对象一样。查询数组中的特定元素时,需要使用方括号[]

$from = 'Arlington Heights, IL 60005, United States';
$remFrom = str_replace(',', '', $from); //Remove Commas
$from = urlencode($remFrom);

$to = 'Arlington Heights, IL 60004, United States';
$remTo = str_replace(',', '', $to); //Remove Commas
$to = urlencode($remTo);

$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data, true);

$time = $data['rows'][0]['elements'][0]['duration']['text']; //Text for String and Value for INT
$distance = $data['rows'][0]['elements'][0]['distance']['text'];//Text for String and Value for INT

echo 'Distance: ' . $distance . '<br>';
echo 'Time: ' . $time;

输出:

Distance: 5.7 km
Time: 11 mins

见:

https://developers.google.com/maps/documentation/distance-matrix/intro

【讨论】:

  • 它与逗号一起工作正常,所以这不是问题。 urlencode 负责处理
  • 谢谢,但信息来自输入文本,所以我怎样才能消除昏迷?
  • @GhadahSalman 逗号将在urlencode() 之后传递,但不需要它们。我会亲自删除除空格之外的所有非单词字符。上面的代码解释了如何使用str_replace() 来执行此操作,只需将$from$to 变量设置为包含您的用户输入变量。
  • 感谢@Kitson88 工作正常但替换 $data = json_decode($data); > $data = json_decode($data,true);
  • @GhadahSalman 不用担心,我的错...我必须在移植到 Stack 时忘记将其设置为关联数组。
猜你喜欢
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 2020-10-06
  • 1970-01-01
  • 2013-08-21
  • 2015-03-30
  • 1970-01-01
相关资源
最近更新 更多