Question

I am new to geocode. I am getting the zip code from the user finding the lat and long and comparing it with a set of nearby locations who latitude and longitude are present in a JSON. So I have to loop through each event to compare. The geocode status is always empty and hence I am not able to get the lat and long for the zipcode which the user has entered.

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

This is my Js function.

self.find_events = function find_events(zip, eventId) {
        var data = LAH.events.events_data,
        matches_found = 0;
        var today = new Date();
        var zip = zip || null;
        var eventId = eventId || null;
        geocoder = new google.maps.Geocoder();
        if(geocoder){       
        geocoder.geocode( { 'address': zip }, function(results, status) { // status is empty
        if (status == google.maps.GeocoderStatus.OK) {
        var userLat = results[0].geometry.location.lat();
        var userLng = results[0].geometry.location.lng();
        userLatLng = results[0].geometry.location;
        }
        });//end geocode        
        } 
        for (var i = data.length-1; i--;) { 
            if (eventId === null) {
                var eventEnd = data[i].endDate;
                var calc_dis = calculateDistance(userLat, userLng, parseFloat(data[i].lat), parseFloat(data[i].lng));
                if ((zip == 'all' || calc_dis === true) && today < eventEnd) {
                    display_event(data[i]);
                    matches_found += 1;
                }               
            }
            else {
                // eventId is valid, only display what we found in the query string
                if (data[i].eventId === parseInt(eventId, 10)) {
                    display_event(data[i]); 
                    matches_found += 1;
                }
            }

        }       
        matches_found ? display_table() : display_no_results();     
        return matches_found;
    };

After the line geocoder.geocode( { 'address': zip }, function(results, status) it skips directly to the for loop.

Was it helpful?

Solution

geocoder.geocode works asyncronously, so you need to wait untill its response will be delivered from google's servers,and only then use reponded data.Put your loop inside of callback:

  geocoder.geocode( { 'address': zip }, function(results, status) { // status is empty
    if (status == google.maps.GeocoderStatus.OK) {
       var userLat = results[0].geometry.location.lat();
       var userLng = results[0].geometry.location.lng();
       userLatLng = results[0].geometry.location;
       for (var i = data.length-1; i--;) { 
          //loop body
       }
    }       
  });//end geocode  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top