【发布时间】:2020-02-06 03:24:29
【问题描述】:
我是新来的。这是我的第一篇文章,但我多年来一直是读者。
多年来,我一直在使用 HTML、CSS、JS 和 PHP,但这已经让我在网上寻求帮助时感到难过。我的问题是,我需要获取传入代码的街道地址的纬度和经度坐标(例如,77 Massachusetts Ave, Cambridge, MA 02139)。
我已经环顾了数周(或数月)并尝试了几个人的建议,这些建议通常是用 JS 或 PHP 编写的。我有一个有效的 Google API 应该可以正常工作(我团队中的其他人已经在 Android 中成功使用它,并且它被标记为能够在我们的网站上工作)。我在多个网站上找到了很多示例,但没有一个有效。
我尝试的一切都没有结果。我意识到谷歌对使用 API 的要求是新的,有些示例没有使用,但即使我应用了我的,也没有任何效果。我正在寻找一个干净、现代的例子来说明如何让这个函数工作。
以下是我尝试过的几个示例。它们什么也没产生,我不确定我是否可以通过错误报告来找出原因:
<?php
function getLatLong($address){
if (!is_string($address))die("All Addresses must be passed as a string");
$_url = sprintf('http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=true&key=[MY_API_KEY]',rawurlencode($address));
if($_result = file_get_contents($_url)) {
$_result = json_decode($_result);
if($_result !== false || !empty($_result->results)) {
return $_result->results[0]->geometry->location;
}
}
return false;
}
$address = "77 Massachusetts Ave, Cambridge, MA 02139";
print_r(getLatLong($address));
$coordinates = getLatLong($address);
$lat = $coordinates['lat'];
$long = $coordinates['long'];
echo $lat.", ".$long;
echo "--";
?>
<?php
$address = '77 Massachusetts Ave, Cambridge, MA 02139'; // Address
$apiKey = '[MY_API_KEY]'; // Google maps now requires an API key.
// Get JSON results from this request
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.$apiKey);
$geo = json_decode($geo, true); // Convert the JSON to an array
if (isset($geo['status']) && ($geo['status'] == 'OK')) {
$latitude = $geo['results'][0]['geometry']['location']['lat']; // Latitude
$longitude = $geo['results'][0]['geometry']['location']['lng']; // Longitude
}
?>
<?php
$dlocation = "77 Massachusetts Ave, Cambridge, MA 02139";
// Get lat and long by address
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false&key=[MY_API_KEY]');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
echo $latitude;
?>
任何帮助将不胜感激!如果您有任何示例代码可以做到这一点,我当然希望看到它。
非常感谢, 发展历程
【问题讨论】:
-
Everything I tried produces nothing。你具体得到什么结果。例如,您能否发布实际结果,因为 nothing 对 Google 来说尤其不寻常。他们返回什么结果?在$output上执行print_r或在$geocode上执行echo。然后将其发布到您的问题。
标签: javascript php google-maps geolocation latitude-longitude