2010-10-28 50 views
8

我有這樣的代碼,其負載谷歌地圖的地理編碼未定義

// Display the map 

function map_it() { 
    var myLatlng = new google.maps.LatLng(13.005621, 77.577531); 
    var myOptions = { 
     zoom: zoomLevel, 
     center: myLatlng, 
     disableDefaultUI: true, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     navigationControl: true, 
     navigationControlOptions: { 
      style: google.maps.NavigationControlStyle.SMALL 
     } 
    } 
    map = new google.maps.Map(document.getElementById("map-it"), myOptions); 
    var marker = new google.maps.Marker({ 
     position: myLatlng, 
     map: map, 
     draggable: true 
    }); 
    google.maps.event.addListener(marker, 'dragend', function (event) { 
     document.getElementById('mapLat').value = marker.getPosition().lat(); 
     document.getElementById('mapLng').value = marker.getPosition().lng(); 
     geocodePosition(marker.getPosition()); 
    }); 
} 

function geocodePosition(pos) { 
    geocoder.geocode({ 
     latLng: pos 
    }, function (responses) { 
     if (responses && responses.length > 0) { 
      updateMarkerAddress(responses[0].formatted_address); 
      alert(responses[0].formatted_address); 
     } else { 
      updateMarkerAddress('Cannot determine address at this location.'); 
     } 
    }); 
} 

initated我得到以下錯誤

geocoder is not defined 
http://localhost/bakasura1/js/modal.js 
Line 74 

回答

34

嗯......呃......它說什麼。您的意思是geocoder.geocode(...),但您尚未定義任何名爲geocoder的變量。你忘了:

var geocoder= new google.maps.Geocoder(); 
+0

ouch:D明白了:D謝謝 – 2010-10-28 17:08:11

+0

同樣的愚蠢的錯誤發生在我身上。謝謝 – RredCat 2012-11-10 14:02:43

+1

這是這個特定情況的答案,但是應該打開一個新的重複問題,因爲這個解決方案不適用? 我確實在代碼的開頭有這一行,我的匿名函數調用它(它不在上面的行之前執行,但onclick)發現它不確定。我在這個函數鏈中的每個函數中都用console.log測試了geocoder,並且他們中的任何一個都可以找到它。這就像在文檔級別有「var geocoder = ...」是不夠的。 – sergio 2014-03-05 02:27:24

4

你有這條線嗎?我沒有在提供的代碼中看到它。

geocoder = new google.maps.Geocoder(); 
1

而且運行JavaScript代碼之前,請確保您有

<script src="https://maps.google.com/maps?file=api&amp;v=3&amp;sensor=false" 
    type="text/javascript"></script> 

這就是搞砸了我。