12

我正在尝试编写一个 Java 应用程序,给定一个城市和一个半径,返回所有附近的城市。我认为 Google Maps API 能够做到这一点,但我对 Places API 没有运气,它只是返回兴趣点(例如餐馆,...)。有没有办法用谷歌 API 做到这一点,或者你会推荐其他一些 API(或这样做的方式)?

4

2 回答 2

13

我编写了一个代码片段,允许您通过结合Google Maps Geocoding APIGeoNames.org API来检索所有附近的城市(除了file_get_contents,您还可以执行cURL请求)。

/*
 * Get cities based on city name and radius in KM
 */

// get geocode object as array from The Google Maps Geocoding API
$geocodeObject = json_decode(file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address={CITY NAME},{COUNTRY CODE}'), true);

// get latitude and longitude from geocode object
$latitude = $geocodeObject['results'][0]['geometry']['location']['lat'];
$longitude = $geocodeObject['results'][0]['geometry']['location']['lng'];

// set request options
$responseStyle = 'short'; // the length of the response
$citySize = 'cities15000'; // the minimal number of citizens a city must have
$radius = 30; // the radius in KM
$maxRows = 30; // the maximum number of rows to retrieve
$username = '{YOUR USERNAME}'; // the username of your GeoNames account

// get nearby cities based on range as array from The GeoNames API
$nearbyCities = json_decode(file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$latitude.'&lng='.$longitude.'&style='.$responseStyle.'&cities='.$citySize.'&radius='.$radius.'&maxRows='.$maxRows.'&username='.$username, true));

// foreach nearby city get city details
foreach($nearbyCities->geonames as $cityDetails)
{
    // do something per nearby city
}

请注意您的请求数量,因为 API 是有限的

有关 API 的更多信息,请访问以下网址:

于 2015-12-03T13:19:56.793 回答
3

您不想使用 Places API 可能是正确的。您可能想看看是否有一种方法可以使用地理编码/反向地理编码来获得您想要的东西。请参阅http://code.google.com/apis/maps/documentation/geocoding/

根据您的性能和准确性要求,您可能无法使用 Google Maps API(或任何其他免费工具)轻松地做到这一点(尤其是在全球范围内),但您可能会得到一些有点工作的东西,特别是如果您有可能简化事情的地理限制(例如,只有美国)。

于 2011-08-26T18:32:12.967 回答