mardi 3 novembre 2015

How to access geocode coordinates outside for loop?

This is similar to this question: HERE. But I still can't work it out. I want to get the lat/lng values from my geocoder but I can't access them outside of the if statement. I know that most things are working because I can access the geocode lat/lng values with console.log() but I can't get them out. I think this has to do with js scope. If I use the code below I get this error: "Uncaught TypeError: Cannot read property 'geocode' of undefined". But If I comment out this part "var myLoc = codeAddress(addressInput);" I can get the array with console.log().

How can get the loc (or each value) array out?

Here is my code.

<script>


    var geocoder;
    var map;

    var addressInput = '<?php 
    echo $_GET["q"]; 
    ?>';
    var loc=[];

    function initialize() {
        geocoder = new google.maps.Geocoder();
        codeAddress(addressInput);
      }

    function codeAddress(address) {
        // next line creates asynchronous request
        geocoder.geocode( { 'address': address}, function(results, status) {
          // and this is function which processes response
          if (status == google.maps.GeocoderStatus.OK) {
            loc[0]=results[0].geometry.location.lat();
            loc[1]=results[0].geometry.location.lng();
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }

            console.log(loc);
// above shows the correct lat/lng values in the console when I comment out the 'myLoc' code below.
        });
        return loc;

          }  
         var myLoc = codeAddress(addressInput);

    google.maps.event.addDomListener(window, 'load', initialize);

    </script> 



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire