2013-09-24 60 views
-1

我想將緯度和經度的值看作全局變量,以便可以使用它。但是,當調用codeAddress()函數時,即使在它完成執行之前,後續的內部警報也會打印出來,並且地圖呈現空白(代碼顯示硬編碼值)。我究竟做錯了什麼?Google Javascript API調用和Geolocator代碼不起作用

var geocoder; 
    var geoloc; 
    var latitude; 
    var longitude 

function codeAddress() { 
    geocoder = new google.maps.Geocoder(); 
    var address = 'Dallas'; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     latitude = results[0].geometry.location.lat();alert(latitude); 
     longitude = results[0].geometry.location.lng();alert(longitude); 

    } else { 
     alert('Geocode was not successful for the following the default location set.reason: ' + status); 
    } 
    }); 
    return; 
} 

function getStoreMap(zoom) 
{ 
codeAddress(); 
google.maps.event.addDomListener(window, 'load', function() { 

    alert("Inside"+latitude); 
    var map = new google.maps.Map(document.getElementById('map-canvas'), { 
    center: new google.maps.LatLng(32.7801399,-96.80045109999998), 
    zoom: zoom, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    var panelDiv = document.getElementById('panel'); 
    var data = new PlacesDataSource(map); 
    var view = new storeLocator.View(map, data,{ updateOnPan: true} 
); 

    var markerSize = new google.maps.Size(24, 24); 
    view.createMarker = function(store) { 
    return new google.maps.Marker({ 
     position: store.getLocation(), 
     icon: new google.maps.MarkerImage(store.getDetails().icon, null, null, 
      null, markerSize) 
    }); 
    }; 

    new storeLocator.Panel(panelDiv, { 
    view: view 
    }); 
}); 

} 
+0

[Google地圖API問題與地理編碼器問題]的可能重複(http://stackoverflow.com/questions/15606660/google-maps-api-issue-with-geocoder) – geocodezip

回答

0

到谷歌API的調用是異步的,所以當你調用codeAddress(),它開始調用可以繼續與代碼的其餘部分。

然後加載文檔,並在文檔加載時調用警報。

在文檔加載完成時並未完成對Google的調用,並且未及時分配經緯度變量。

在加載時設置您的文檔以初始化地圖並進行地理定位調用。在地理定位調用的完整功能上,調用另一個函數將根據結果修改地圖。