在本文中,我们将知道如何使用PHP中的Google Maps API从纬度和经度获取地址。
其中我们将提供一个简单的PHP脚本,从纬度和经度获取位置。
整个脚本组合成PHP功能,我们只需要使用此功能来查找纬度和经度的地址。
'getAddress()'函数接受两个参数纬度,经度('$latitude','$longitude'),我们需要从我们想要获取地址的位置提供纬度和经度。
如果找到,此函数基于给定的纬度和经度的地址返回,否则返回false。
用法:
使用'getAddress()'功能如下。
$latitude = '38.897952'; $longitude = '-77.036562'; $address = getAddress($latitude,$longitude); $address = $address?$address:'Not found';
'getAddress()'功能如下:
/** * Author: onitroad * Author URI: http://www.onitroad.com * Function Name: getAddress() * $latitude => Latitude. * $longitude => Longitude. * Return => Address of the given Latitude and longitude. **/ function getAddress($latitude,$longitude){ if(!empty($latitude) && !empty($longitude)){ //Send request and receive json data by address $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; //Get address from json data $address = ($status=="OK")?$output->results[1]->formatted_address:''; //Return address of the given latitude and longitude if(!empty($address)){ return $address; }else{ return false; } }else{ return false; } }
要在请求中指定“Google API密钥”,请将其包含为键参数的值。
$geocodeFromLatLong = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($latitude).','.trim($longitude).'&sensor=true_or_false&key=GoogleAPIKey');
日期:2020-06-02 22:15:30 来源:oir作者:oir