2012-07-25 42 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的訪問欲瞭解更多信息,以下網址:

相關問題