12

I have this code which is initated on load

// 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.');
        }
    });
}

i get the following error

geocoder is not defined
http://localhost/bakasura1/js/modal.js
Line 74
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

3 Answers3

42

Well... er... what it says. You're saying geocoder.geocode(...), but you've not actually defined any variable called geocoder. Did you forget:

var geocoder= new google.maps.Geocoder();
bobince
  • 528,062
  • 107
  • 651
  • 834
  • 1
    This was the answer for THIS specific case, but should a new duplicate question be opened just because this solution doesn't apply? I do have that line at the beginning of the code, and my anonymous function that calls it (which doesn't execute before the above line, but onclick) finds it undefined. I tested the geocoder with console.log inside every function in the chain of functions this one is in, and NONE of them can find it. It's like having "var geocoder=..." at document level wasn't enough. – sergio Mar 05 '14 at 02:27
  • Hmm, yeah, sounds like a different problem to me! Suggest posting with a minimal reproducible test case. – bobince Mar 05 '14 at 10:13
5

Do you have this line somewhere? I don't see it in the code provided.

geocoder = new google.maps.Geocoder();
Paul U
  • 671
  • 6
  • 7
2

Also make sure you have

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

prior to running the javascript code.

That's what messed me up.