我需要从一个地址获取经度和纬度

问题描述 投票:0回答:1

我是新来的。这是我的第一篇文章,但多年来我一直是读者。

我已经使用HTML,CSS,JS和PHP多年了,但这在我在线寻求帮助的地方感到很沮丧。我的问题是我需要获取传入代码的街道地址的纬度和经度坐标(例如,马萨诸塞州大街77号,剑桥,MA 02139)。

我已经环顾了几周(或几个月),并尝试了一些人的建议,这些建议通常是用JS或PHP编写的。我有一个有效的Google API,该API应该可以正常运行(我团队中的其他人已经在Android中成功使用它,并且被标记为可以在我们的网站上运行)。我在多个站点上发现了很多示例,但没有用。

我尝试过的所有方法都不会产生任何效果。我意识到Google使用API​​的要求是新的,有些示例没有使用API​​,但是即使我使用我的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;
?>

任何帮助将不胜感激!如果您有任何可以执行此操作的示例代码,我当然希望看到它。

非常感谢,BDP

javascript php google-maps geolocation latitude-longitude
1个回答
0
投票

我使用此api来获取用户输入的城市的纬度和经度。请参阅文档以获取适当的预期结果。

使用帐户注册,您将获得唯一的密钥。链接:https://account.mapbox.com/auth/signup/

https://api.mapbox.com/geocoding/v5/mapbox.places/ {city} .json?access_token = {key}&limit = 1`

© www.soinside.com 2019 - 2024. All rights reserved.