Domanda

Sono nuovo al geocodo.Sto ricevendo il codice postale dall'utente, trovando il lat e lungo e confrontandolo con una serie di posizioni vicine che latitudine e longitudine sono presenti in un JSON.Quindi devo andare in loop attraverso ogni evento per confrontare.Lo stato del geocode è sempre vuoto e quindi non sono in grado di ottenere il lat e lungo per il codice postale che l'utente è stato inserito.

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

Questa è la mia funzione JS.

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;
    };
.

Dopo la linea geocoder.geoocodice ({'indirizzo': zip}, funzione (risultati, stato) Salta direttamente al per loop .

È stato utile?

Soluzione

geocoder.geocode funziona Asyncronialy , quindi è necessario attendere che la sua risposta verrà consegnata dai server di Google, e solo quindi utilizzare i dati riposti. Metti il tuo loop all'interno di 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  
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top