【问题标题】:Get location from latitude and longitude in PHP从PHP中的纬度和经度获取位置
【发布时间】:2015-04-14 09:45:07
【问题描述】:

我想在不同的变量中获取 address、city、statecountry 以便我可以单独显示它,但由于 latlong 不同,我在某处获得了完整的地址而某处只有州和国家,所以由于纬度变化,我无法获得具体地址。

这是我的代码:

$geoLocation=array();
$URL = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=8.407168,6.152344&sensor=false';
$data = file_get_contents($URL);
$geoAry = json_decode($data,true);
for($i=0;$i<count($geoAry['results']);$i++){
   if($geoAry['results'][$i]['types'][0]=='sublocality_level_1'){
     $address=$geoAry['results'][$i]['address_components'][0]['long_name'];
     $city=$geoAry['results'][$i]['address_components'][1]['long_name'];
     $state=$geoAry['results'][$i]['address_components'][3]['long_name'];
     $country=$geoAry['results'][$i]['address_components'][4]['long_name'];
     break;
  }
  else {
     $address=$geoAry['results'][0]['address_components'][2]['long_name'];
     $city=$geoAry['results'][0]['address_components'][3]['long_name'];
     $state=$geoAry['results'][0]['address_components'][5]['long_name'];
     $country=$geoAry['results'][0]['address_components'][6]['long_name'];
  }
}
$geoLocation = array(
  'city'=>$city,
  'state'=>$state,
  'country'=>$country,
  'address'=>$address
);
print_r($geoLocation);

【问题讨论】:

    标签: php google-maps geolocation


    【解决方案1】:

    试试下面的一个:

    <?php 
    $geolocation = $latitude.','.$longitude;
    $request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false'; 
    $file_contents = file_get_contents($request);
    $json_decode = json_decode($file_contents);
    if(isset($json_decode->results[0])) {
        $response = array();
        foreach($json_decode->results[0]->address_components as $addressComponet) {
            if(in_array('political', $addressComponet->types)) {
                    $response[] = $addressComponet->long_name; 
            }
        }
    
        if(isset($response[0])){ $first  =  $response[0];  } else { $first  = 'null'; }
        if(isset($response[1])){ $second =  $response[1];  } else { $second = 'null'; } 
        if(isset($response[2])){ $third  =  $response[2];  } else { $third  = 'null'; }
        if(isset($response[3])){ $fourth =  $response[3];  } else { $fourth = 'null'; }
        if(isset($response[4])){ $fifth  =  $response[4];  } else { $fifth  = 'null'; }
    
        if( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth != 'null' ) {
            echo "<br/>Address:: ".$first;
            echo "<br/>City:: ".$second;
            echo "<br/>State:: ".$fourth;
            echo "<br/>Country:: ".$fifth;
        }
        else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth == 'null'  ) {
            echo "<br/>Address:: ".$first;
            echo "<br/>City:: ".$second;
            echo "<br/>State:: ".$third;
            echo "<br/>Country:: ".$fourth;
        }
        else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth == 'null' && $fifth == 'null' ) {
            echo "<br/>City:: ".$first;
            echo "<br/>State:: ".$second;
            echo "<br/>Country:: ".$third;
        }
        else if ( $first != 'null' && $second != 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
            echo "<br/>State:: ".$first;
            echo "<br/>Country:: ".$second;
        }
        else if ( $first != 'null' && $second == 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
            echo "<br/>Country:: ".$first;
        }
      }
    ?>
    

    【讨论】:

    • @SHAZ 它与 API 密钥和 SSL 一起工作,否则它工作一两次,然后给出错误“您已超出此 API 的每日请求配额。”
    • @SHAZ 你怎么看?
    • 是的,需要 API 密钥意味着您必须登录谷歌的开发者帐户并启用地图服务并获取您创建的项目的密钥。谷歌现在也弃用了传感器
    • file_get_contents() 出于安全原因已被禁用。
    • @MuhammedShihabudeenLabbaA 你可以使用“CURL”而不是“file_get_contents()”
    【解决方案2】:

    使用 Google Geocode API 从纬度和经度获取位置。

    这里有一个简单的 PHP 脚本。

    $latitude = 'Insert Latitude';
    $longitude = 'Insert Longitude';
    
    $geocodeFromLatLong = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($latitude).','.trim($longitude).'&sensor=false'); 
    $output = json_decode($geocodeFromLatLong);
    $status = $output->status;
    $address = ($status=="OK")?$output->results[1]->formatted_address:'';
    

    以上源码可以从这里找到-Get Address from Latitude and Longitude using Google Maps API and PHP

    【讨论】:

      【解决方案3】:

      在此处查看 Google 地理编码 API:https://developers.google.com/maps/documentation/geocoding

      在您的情况下,location_type 设置为“APPROXIMATE” 这意味着返回的结果不是精确的地理编码,这意味着您不会拥有完整的地址。

      【讨论】:

        【解决方案4】:

        我正在使用 codeigniter 并且有类似的要求,这就是我得到它的方式

            <script>
                            var lt=pos.lat;
                            var lon=pos.lng;
                            var current_lat=$("#current_lat").val(lt);
                            var current_long=$("#current_long").val(lon);
        
            </script>
        

        HTML:

           <input type="hidden" id="current_lat" name="current_lat" value="<?php echo $this- 
         >session->userdata('current_lat');?>">
                                <input type="hidden" id="current_long" name="current_long" 
         value="<?php echo $this->session->userdata('current_long');?>">
        

        PHP:

                $current_long= $this->input->post('current_long');
                $current_lat=$this->input->post('current_lat');
                $newdata = array(
        
                           'current_lat'     => $current_lat,
                           'current_long'     => $current_long
                       );
        
                       $this->session->set_userdata($newdata);  
        
        

        【讨论】:

          【解决方案5】:

          如果你使用 laravel 那么它对你很有用

              $latitude=26.12312;
              $longitude=83.77823;
              $geolocation = $latitude.','.$longitude;
              $response = \Http::get('https://maps.googleapis.com/maps/api/geocode/json', [
                  'latlng' => $geolocation,
                  'key' => 'api key',
                  'sensor'    =>  false
              ]);
              $json_decode = json_decode($response);
              if(isset($json_decode->results[0])) {
                  $response = array();
                  foreach($json_decode->results[0]->address_components as $addressComponet) {
                      $response[] = $addressComponet->long_name;
                  }
                  dd($response);
              }
          

          请用您自己的替换 api 密钥

          【讨论】:

            【解决方案6】:

            上述解决方案将不起作用,因为谷歌现在需要 API KEY 来获取数据:

            这是一个简单的函数,它将返回 latlong 以及 google_place_id

            function geoLocate($address)
            {
                try {
                    $lat = 0;
                    $lng = 0;
            
                    $data_location = "https://maps.google.com/maps/api/geocode/json?key=".$GOOGLE_API_KEY_HERE."&address=".str_replace(" ", "+", $address)."&sensor=false";
                    $data = file_get_contents($data_location);
                    usleep(200000);
                    // turn this on to see if we are being blocked
                    // echo $data;
                    $data = json_decode($data);
                    if ($data->status=="OK") {
                        $lat = $data->results[0]->geometry->location->lat;
                        $lng = $data->results[0]->geometry->location->lng;
            
                        if($lat && $lng) {
                            return array(
                                'status' => true,
                                'lat' => $lat, 
                                'long' => $lng, 
                                'google_place_id' => $data->results[0]->place_id
                            );
                        }
                    }
                    if($data->status == 'OVER_QUERY_LIMIT') {
                        return array(
                            'status' => false, 
                            'message' => 'Google Amp API OVER_QUERY_LIMIT, Please update your google map api key or try tomorrow'
                        );
                    }
            
                } catch (Exception $e) {
            
                }
            
                return array('lat' => null, 'long' => null, 'status' => false);
            }
            

            【讨论】:

              猜你喜欢
              • 2012-11-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-05-14
              • 1970-01-01
              • 1970-01-01
              • 2021-09-29
              相关资源
              最近更新 更多