2

So; I am developing this web application that works based on the location of the user.

The part that finds the coordinates and the part that converts those coordinates into an address both work individually. However the variable from the first function doesn't seem to transfer over to do the second function and I can't figure out why.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>

<script type="text/javascript">

var coordinates;


function getCoordinates(){

  var options = {
    enableHighAccuracy: true,
    timeout: 4500,
    maximumAge: 0
  };

  function success(pos) {
    var crd = pos.coords;

    console.log('Enlem : ' + crd.latitude);
    console.log('Boylam: ' + crd.longitude);
    console.log('Hata Payı ' + crd.accuracy + ' metre.');

    coordinates = new google.maps.LatLng(crd.latitude, crd.longitude);
    alert(coordinates);
    return coordinates;

   };

  function error(err) {
    console.warn('HATA(' + err.code + '): ' + err.message);
  };

  navigator.geolocation.getCurrentPosition(success, error, options);
 }


 var ReverseGeocode = function () {

    //This is declaring the Global variables

    var geocoder, map, marker;

    //This is declaring the 'Geocoder' variable
    geocoder = new google.maps.Geocoder();

    function GeoCode(latlng) {

        // This is making the Geocode request
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {

            if(status !== google.maps.GeocoderStatus.OK)
            {
                alert(status);
            }
            // This is checking to see if the Geoeode Status is OK before proceeding    
            if (status == google.maps.GeocoderStatus.OK) {

                var address = (results[0].formatted_address);

                //This is placing the returned address in the 'Address' field on the HTML form  
                document.getElementById('Address').value = results[0].formatted_address;


            }
        });

    }

    return {

        Init: function () {

            var latlng = getCoordinates();

            alert(latlng);
            GeoCode(latlng);
        },

    };

} ();           


</script>

</head>
<body>
    <div>
        <input name="Address" type="text" id="Address" size="55" />
    </div>
    <div>
        <input type="button" value="Adres Bul" onclick="ReverseGeocode.Init()">
    </div>
    <div id="map_canvas" style="height: 90%; top: 60px; border: 1px solid black;">
    </div>
</body>
</html>
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Code Bunny
  • 447
  • 1
  • 5
  • 23
  • One thing I noticed is the alert(latLng) - captial L - so, the issue may not be what you think it is, just the alert is wrong – Jaromanda X Jul 06 '15 at 12:23
  • Oh that typo happened when I was transferring the code over here. I will change it to how it is in the original code. Thank you. – Code Bunny Jul 06 '15 at 12:26
  • Look at my post here, I think this is what you need http://stackoverflow.com/questions/27203977/google-api-address-components#27226620 – Emmanuel Delay Jul 06 '15 at 12:37
  • I'm not sure how these are related? I clarified the title sticking to the important aspects of my problem. parsing the district out of the string is not an issue actually. – Code Bunny Jul 06 '15 at 13:29

1 Answers1

1

Your main problem: getCoordinates() does not return coordinates. So you cannot use it like this:

var latlng = getCoordinates();

Javascript has asyncronous stuff. That means it takes javascript some time to do it.

The way javascript handles this: You send a request, and you provide a callback (a function). Whenever javascript is ready, your callback will be executed. Positioning is one of those asynchronic things.

Here is a short example:

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
  <script type="text/javascript">
  // this function is triggered when geolocation has found coordinates
  function geolocationReturnedCoordinates(coordinates) {
    document.getElementById('log').innerHTML = 
      'lat: ' + coordinates.coords.latitude +
      '<br>lng: ' + coordinates.coords.longitude +
      '<br>accuracy: ' + coordinates.coords.accuracy;
    // Here would be a good place to call Reverse geocoding, since you have the coordinates here.
    GeoCode(new google.maps.LatLng(coordinates.coords.latitude, coordinates.coords.longitude));
  }

  // geocoder
  geocoder = new google.maps.Geocoder();
  function GeoCode(latlng) {
    // This is making the Geocode request
    geocoder.geocode({'location': latlng }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var address = (results[0].formatted_address);
        //This is placing the returned address in the 'Address' field on the HTML form  
        document.getElementById('Address').value = results[0].formatted_address;
      }
    });
  }

  function search_position_and_address() {
    // we start the request, to ask the position of the client
    // we will pass geolocationReturnedCoordinates as the success callback
    navigator.geolocation.getCurrentPosition(geolocationReturnedCoordinates, null, null);
  }
  </script>
</head>
<body>
  <input type="button" value="GO" onclick="search_position_and_address()"> Get position (coordinates) of the client.  -- Then look for the address
  <div id="log"></div>
  <input id="Address" placeholder="Address">
</body>
</html>

It's up to you to put it back in your structure. I just compiled the shortest code that permitted me to make my point.

Also the names of the functions ... I'm trying to make a point. In real life you would pick a shorter name.

Emmanuel Delay
  • 3,619
  • 1
  • 11
  • 17