我有一个这样的网址,可以在某个位置搜索内容:
https://maps.google.com/maps?q=dentist+Austin+Texas&hl=en&mrt=yf=l
我需要前 2 个结果的列表,例如(“牙医
Mr.Example1”,”Dentist Ex.2”)。
这是一个 Google Maps API 请求。
给你:
$searchTerm = 'dentist+austin+texas';
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $searchTerm;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$array = json_decode($response, true);
// var_dump($array);
// Output
$array = $array['results'];
foreach($array as $index => $component)
{
echo '#' . $index . ' ' . $component['formatted_address'] . '<br>';
// show only the first 2 items (#0 & #1)
if($index === 1) {
break;
}
}
一些注意事项:
参考:https://developers.google.com/maps/documentation/geocoding/
这几乎是完美的,但我还想获得电话号码和排名(评论的星星)。
最初的问题是使用 Google Maps API 列出德克萨斯州奥斯汀牙医的第一个结果。
此附加要求会更改要使用的 API/Web 服务,以便检索丰富的数据。您想要更多关于地址的details。
数据元素“phone_number”和“rating”是Google Places Webservice (Place Details) 的一部分。您需要将密钥添加到请求 URL (&key=API_KEY) 才能访问此服务。
https://developers.google.com/places/webservice/details#PlaceDetailsRequests
这是一个地方详情请求:
1) 从第一个请求中提取“place_id”。
2) 对于后续请求,您可以通过“地点详细信息”网络服务检索每个地点的详细信息。
示例:这里我使用placeid 作为第一个条目:
新代码:
<?php
// Google GeoCode API
$address = 'dentist+austin+texas';
$array = getGoogleGeoCode($address);
$array = $array['results'];
//var_dump($array);
foreach($array as $index => $component)
{
echo '#' . $index . ' ' . $component['formatted_address'] . ', ' ;
// subsequent request for "Place Details"
$details = getGooglePlaceDetails($component['place_id']);
$details = $details['result'];
//var_dump($details);
echo 'Phone: ' . $details['formatted_phone_number']. ', ' ;
// rating contains the place's rating, from 1.0 to 5.0, based on aggregated user reviews.
if(isset($details['rating'])) {
echo 'Rating: ' . $details['rating'];
}
// show only the first two entries
/*if($index === 1) {
break;
}*/
echo '<br>';
}
function getGooglePlaceDetails($placeid)
{
// your google API key
$key = 'AIzaSyCj9yH5x6_5_Om8ebAO2pBlaqJZB-TIViY';
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=' . $placeid . '&key=' . $key;
return curlRequest($url);
}
function getGoogleGeoCode($address)
{
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address;
return curlRequest($url);
}
function curlRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
结果:
- 数组元素
rating 并不总是存在,因为它是基于审查的。只需使用 var_dump($details); 即可查看其中的内容并选择您需要的内容。
- 要减少列表,请删除 break 语句周围的 cmets。