2011-05-26 39 views
35

使用Google Maps API v3,有沒有辦法在初始化時設置地圖的中心?我已經使用這個代碼的解決方法:Google Maps v3 - 如何在初始化時使用地址居中?

var geocoder; 
    var map; 
    function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 
    var myOptions = { 
     zoom: 8, 
     center: latlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    } 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    codeAddress('germany'); 
    } 

    function codeAddress(address) { 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     map.setCenter(results[0].geometry.location); 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location 
     }); 
     } 
    }); 
    } 

唯一的問題是,當初始化時,它是中心的「經緯度」的一瞬間。我無法弄清楚如何在「myOptions」中設置中心。我雖然可以從codeAddress函數返回「results [0] .geometry.location」並將其傳遞給myOptions,但這不起作用。

感謝您的任何幫助。

更新 由於我不能完全刪除「中心」,我想知道是否有辦法將地址傳遞給選項。

從谷歌API:

要初始化地圖,我們需要先創建一個Map options對象包含地圖初始化變量。 該物體未構造;相反,它被創建爲對象文字。每個地圖有兩個要求 選項:中心放大

回答

70

那麼一個簡單的解決辦法是初始化地圖在codeAddress功能:

var geocoder, map; 

function codeAddress(address) { 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 
     'address': address 
    }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var myOptions = { 
       zoom: 8, 
       center: results[0].geometry.location, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      } 
      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

      var marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location 
      }); 
     } 
    }); 
} 

這應該解決的問題。

+2

我一直試圖在初始化函數中包含地理編碼函數......但它實際上是另一種方式。謝謝! – TerryMatula 2011-05-26 18:05:11

相關問題