2013-03-25 145 views
0

我想我只是在做一些愚蠢的事情,因爲我的JavaScript技能並不是最棒的。下面的代碼會產生一個空白的,灰色地圖:Google maps API地理編碼問題

function initialize() { 
     directionsDisplay = new google.maps.DirectionsRenderer(); 
     geocoder = new google.maps.Geocoder(); 
     var address = "Minneapolis, MN"; 
     geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) 
      { 
       lat = results[0].geometry.location.lat(); 
       lng = results[0].geometry.location.lng(); 
       addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng()); 
      } 
      else 
      { 
        alert(status); 
      } 
     }); 
     var mapOptions = { 
      zoom: 7, 
      mapTypeId: google.maps.MapTypeId.ROADMAP, 
      center: addresslatlng 
     }; 
     var map = new google.maps.Map(document.getElementById('map-canvas'), 
      mapOptions); 
     directionsDisplay.setMap(map); 
     directionsDisplay.setPanel(document.getElementById('directions-panel')); 
     } 

然而,如果簡單地改變 「中心:addresslatlng」 到:

center: new google.maps.LatLng(-34.397, 150.644) 

它工作正常。

我嘗試使用LATLNG而無法正常工作或:

center: new google.maps.LatLng(lat, lng) 

任何想法?

回答

1

地理編碼是異步的。您需要使用回調函數裏面的結果:

function initialize() { 
    directionsDisplay = new google.maps.DirectionsRenderer(); 
    geocoder = new google.maps.Geocoder(); 
    var address = "Minneapolis, MN"; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) 
     { 
      lat = results[0].geometry.location.lat(); 
      lng = results[0].geometry.location.lng(); 
      addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng()); 
    var mapOptions = { 
     zoom: 7, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     center: addresslatlng 
    }; 
    var map = new google.maps.Map(document.getElementById('map_canvas'), 
     mapOptions); 
    directionsDisplay.setMap(map); 
    directionsDisplay.setPanel(document.getElementById('directions-panel')); 
     } 
     else 
     { 
       alert(status); 
     } 
    }); 
    } 

working example

+0

現在的工作,謝謝! – XanderNGCC 2013-03-25 02:41:59

0

我覺得這

lat = results[0].geometry.location.lat(); 
lng = results[0].geometry.location.lng(); 

真的應該更喜歡這個

lat = results[0].geometry.location.lat; 
lng = results[0].geometry.location.lng; 

還創建latlon再不用在下一行中使用它們。 更改此

addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng()); 

這個

addresslatlng = new google.maps.LatLng(lat, lng);