【问题标题】:How to get longitude and latitude of any address?如何获取任何地址的经度和纬度?
【发布时间】:2011-04-18 00:03:39
【问题描述】:

您好,如果我在 PHP 中有 street_name、State_name、City_name、Country_name 和邮政编码,获取任何地址的经度和纬度的公式是什么? 谢谢

【问题讨论】:

标签: php


【解决方案1】:

使用以下代码获取 lat 和 long 使用 php。这里有两种方法:

类型 1:

    <?php
     // 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');
        $output= json_decode($geocode);
        $latitude = $output->results[0]->geometry->location->lat;
        $longitude = $output->results[0]->geometry->location->lng;

?>

编辑 - 谷歌地图请求必须通过 https

类型 2:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
     <script>
      var geocoder;
      var map;
      function initialize() {
        geocoder = new google.maps.Geocoder();
         var latlng = new google.maps.LatLng(50.804400, -1.147250);
        var mapOptions = {
         zoom: 6,
         center: latlng
        }
         map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
        }

       function codeAddress(address,tutorname,url,distance,prise,postcode) {
       var address = address;

        geocoder.geocode( { 'address': address}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
           var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });

      var infowindow = new google.maps.InfoWindow({
         content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
       });
        infowindow.open(map,marker);

          } /*else {
          alert('Geocode was not successful for the following reason: ' + status);
        }*/
       });
     }


      google.maps.event.addDomListener(window, 'load', initialize);

     window.onload = function(){
      initialize();
      // your code here
      <?php foreach($addr as $add) { 

      ?>
      codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
      <?php } ?>
    };
      </script>

     <div id="map-canvas12"></div>

【讨论】:

  • 这正是我想要的。谢谢!我能问一个问题吗?我只需要这个功能来进行内部计算。 API 文档明确指出 API 只能与 Google 地图服务结合使用。您的代码示例是否处于这种情况?
  • 在类型 1 中,我收到“您已超出此 API 的每日请求配额。”作为几次测试后的错误消息......没有获得每日请求配额的任何解决方法?
  • 需要在上面的 PHP 示例中将“&key=API_KEY”添加到 URL 的末尾,否则您可能会遇到超出配额的问题。例如maps.googleapis.com/maps/api/geocode/… 更多信息在这里:developers.google.com/maps/documentation/geocoding
  • 确保在file_get_contents 行的php 版本中添加https://,否则它将返回Array ( [error_message] =&gt; Requests to this API must be over SSL. Load the API with "https://" instead of "http://". [results] =&gt; Array ( ) [status] =&gt; REQUEST_DENIED ) NULL
  • urlencode() 会不会更好地准备地址,因为“&”会搞砸一切,而不是用“+”替换空格?
【解决方案2】:
<?php
$address = 'BTM 2nd Stage, Bengaluru, Karnataka 560076'; // Address
$apiKey = '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
}
?>

【讨论】:

  • 仅供其他人使用,如果您无法检索它们,请打印 $geo 变量以查看发生的错误。对我来说,我必须使用 API 密钥,在查询中使用 (&key=[API_KEY]) 和 https 指定。
  • @DirtyBit:你让我很尴尬。 :D 很高兴再次见到你。
【解决方案3】:

您需要访问地理编码服务(即来自 Google),没有简单的公式可以将地址转换为地理坐标。

【讨论】:

    【解决方案4】:

    您可以为此使用 Google Maps API。有关详细信息,请参阅下面的博客文章。

    http://stuff.nekhbet.ro/2008/12/12/how-to-get-coordinates-for-a-given-address-using-php.html

    【讨论】:

      【解决方案5】:

      PHP 有一些很好的内置函数来获取地理位置。也许看看这里:http://php.net/manual/en/ref.geoip.php

      根据php手册,“此扩展需要安装GeoIP C库版本1.4.0或更高版本。您可以从»http://www.maxmind.com/app/c获取最新版本并自行编译。”

      【讨论】:

        【解决方案6】:

        考虑到传入的垃圾和 file_get_contents 失败....

        function get_lonlat(  $addr  ) {
            try {
                    $coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
                    $e=json_decode($coordinates);
                    // call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
                    if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
                    // $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
                    if ( $coordinates == false   ||  $err_res ==  true  ) {
                        $a = array( 'lat'=>0,'lng'=>0);
                        $coordinates  = new stdClass();
                        foreach (  $a  as $key => $value)
                        {
                            $coordinates->$key = $value;
                        }
                    } else {
                        // call to google ok so just return longitude/latitude.
                        $coordinates = $e;
        
                        $coordinates  =  $coordinates->results[0]->geometry->location;
                    }
        
                    return $coordinates;
            }
            catch (Exception $e) {
            }
        

        然后得到绳子: 其中 $pc 是邮政编码或地址.... $address = get_lonlat($pc); $l1 = $地址->纬度; $l2 = $地址->lng;

        【讨论】:

          【解决方案7】:

          没有论坛,因为街道名称和城市基本上是随机分配的。该地址需要在数据库中查找。或者,您可以在数据库中查找邮政编码所在地区的邮政编码。

          你没有提到国家,所以我假设你只想要美国的地址。您可以使用许多数据库,有些是免费的,有些不是。

          您还可以使用 Google Maps API 让他们在他们的数据库中为您查找地址。这可能是最简单的解决方案,但要求您的应用程序始终具有有效的互联网连接。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-10-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多