2011-05-22 33 views
6

我有一個關於在不同國家遠足的頁面。我試圖爲每個國家創建一個類似的頁面,但不知道如何自動將谷歌地圖集中在一個國家周圍,並根據國家的大小調整焦點。如何在國家周圍放置谷歌地圖如果您只有國家名稱

這裏是我的問題網頁:

http://www.comehike.com/outdoors/country.php?country_id=6&country_name=Belarus

http://www.comehike.com/outdoors/country.php?country_id=1&country_name=United%20States

你看中心和焦點尺寸如何是靜態的?那是因爲我目前使用此代碼將地圖:

function initialize() 
{ 
    var myLatlng = new google.maps.LatLng(37.775, -122.4183333); 

    var myOptions = 
    { 
     zoom: 2, 
     center: myLatlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    } 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
} 

不過,這只是因爲我不知道如何通過國家名稱做,並自動調整大小。我如何通過將國家名稱傳入初始化函數來完成這一切?

謝謝!

回答

11

您可以使用Geocoding service將國家/地區名稱轉換爲座標。 Google提供的示例集中了一張地圖,但未放大地圖。要縮放它,您應該使用map.fitBounds()方法,使用地理編碼器返回的LatLngBounds對象。 這是一個示例代碼:

var myLatlng = new google.maps.LatLng(37.775, -122.4183333); 

var myOptions = 
{ 
    zoom: 2, 
    center: myLatlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
} 
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

var address = "Belarus"; 
var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     map.setCenter(results[0].geometry.location); 
     map.fitBounds(results[0].geometry.bounds); 
    } else { 
     alert("Geocode was not successful for the following reason: " + status); 
    } 
}); 
+0

尤里我仍然得到一些JS錯誤..這裏有一個例子頁:http://www.comehike.com/outdoors/country.php?country_id=1&country_name=United %20States – Genadinik 2011-05-22 06:49:02

+1

你有這樣一個錯誤:' initialize(United States);「>',你應該加引號:' initialize('United States');」> – 2011-05-22 06:57:58

相關問題