2012-07-25 43 views
0

我想查找澳大利亚哪个城市的最近城市example在此查看示例。我尝试过使用Google API,但没有用。我该如何实现这一目标。你可以帮帮我吗?如何在Google地图API中找到距离最近的城市

代码

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

    var request = { 
     location: fenway, 
     radius: 500, 
     types: ['store'] 
    }; 
    var service = new google.maps.places.PlacesService(map); 
    service.search(request, callback); 

    function callback(results, status) { 
     if (status == google.maps.places.PlacesServiceStatus.OK) { 
      for (var i = 0; i < results.length; i++) { 
       var lat = results[i].geometry.location.lat(); 
       var geocoder = new google.maps.Geocoder(); 
       var lng = results[i].geometry.location.lng(); 
       var latlng = new google.maps.LatLng(lat, lng); 
       geocoder.geocode({ 
        'latLng': latlng 
       }, function (result, status1) { 
        if (status == google.maps.GeocoderStatus.OK) { 
         if (result[1]) { 
          console.log(result[1]); 
         } 
        } else { 
         alert("Geocoder failed due to: " + status1); 
        } 
       }); 

      } 
     } 
    } 

我想在城市附近不喜欢商店等。我必须找到在澳大利亚郊区有哪些近,而我给

+0

我添加了我的代码,我试过了。你有什么建议吗? – muthu 2012-07-25 12:27:10

+0

以前也曾经有过相同的问题:http://stackoverflow.com/search?q=nearest+towns+cities&submit=search – Marcelo 2012-07-25 12:56:50

回答

1

我写了一个郊区代码片段,让您在谷歌地图API地理编码和GeoNames.org API(合并除了一个的file_get_contents检索附近的所有城市你也可以做一个卷曲请求)。

/* 
* 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的访问欲了解更多信息,以下网址:

相关问题