如何计算两点之间的公里数?

How can I calculate the KM's between two points?

我一直在一个网站上工作,它的功能之一是预算制定者,也就是说,用户可以在这里找到他们会为他们选择的服务花费多少,然而,谷歌API 是付费的,目前,对于这个项目,我这样做是不可行的,我一直在尝试使用微软的 Bing 地图 API,但是全部都是“URLs”和JSON,我有点不知所云,谁能向我解释一下我需要做什么来“解码”JSON 文件并获取距离参数?

文档:https://docs.microsoft.com/en-us/bingmaps/rest-services/routes/calculate-a-route

我的URL代码:“http://dev.virtualearth.net/REST/v1/Routes?wayPoint.1=$startAdress&viaWaypoint.2=$UserInputedAdress&travelMode=Driving&optimize=distance&distanceUnit=km&key=BingMapsKey";

我的解码代码json - print_r(json_decode($distanciaBing)); (始终 returns '1',无论输入如何。

这实际上取决于 $distanciaBing 来自您的问题。我会推断那是一个包含你需要解析的查询数据的字符串。

从那里开始,只需找到您实际需要的 JSON 数据的开头和结尾。

在硬编码之前,您必须(首先)手动执行此操作。只需在 return 结果中手动定位 开始 JSON 字符串的独特 内容即可。同样,手动找到以 JSON 字符串结尾的唯一内容。然后你将能够从 $distanciaBing.

中提取它

例如

$uniqueStart = ""; // replace what you found on that which is unique that is just before the JSON string

$uniqueEnd = ""; // replace what you found on that which is unique just after the JSON string

$jsonBeginCharPos = strpos($distanciaBing, $uniqueStart) + strlen($uniqueStart);

$jsonEndCharPos = strpos($distanciaBing, $uniqueEnd) - 1;

$jsonStringNeeded = substr($distanciaBing, $jsonBeginCharPos, ($jsonEndCharPos - $jsonBeginCharPos) + 1);

在后者,我们提取我们想要的字符串,即 JSON 字符串。 如果在手动测试中这最终成为我们想要的字符串,那么我们可以硬编码此功能。

到目前为止,我们已经成功提取了 json 字符串,现在可以通过 PHP 的说法将其转换为关联数组:

$jsonArray = json_decode( $jsonStringNeeded, true );

从这里您可以做任何需要做的事情来使用这些数据。

对于将来遇到此问题的人来说可能是值得的 post,因此:这是从 JSON 中取回对象的修复方法:

$getDistance = "http://dev.virtualearth.net/REST/v1/Routes?o=xml&wp.0=$startAdress&wp.1=$endAdress&travelMode=Driving&optimize=distance&distanceUnit=km&key=(bingKey)";

$fileContents = file_get_contents($getDistance);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);

$json = json_encode($simpleXml);
$obj= json_decode($json);

$TravelDistance = $obj->ResourceSets->ResourceSet->Resources->Route->TravelDistance; 

从 JSON 到 XML 再到 JSON 和 'encode' 有点奇怪,然后最后一次解码它才能访问每个字段都经过它的对象。