0

I'm attempting to use the Google geocoder API to enter user's location information directly into a form (reverse geocoding). I am using the most popular answer in this post as a code base.

My form is correctly populated when I use body onload="initialize()" as shown in that answer. However when I attempt to initiate the function using a button nothing happens (I remove the body onload attribute). I have tried the following two variations.

<a href="javascript:;" style="center" onclick="initiate()" class="button">Get Geolocation data</a>

<input type="button" value="Get Geolocation Data" onclick="initiate()">

Could someone please point out my mistake? Full code is as follows:

    <!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"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

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



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 

Many thanks in advance.

Community
  • 1
  • 1
M4bhat
  • 43
  • 1
  • 1
  • 5

3 Answers3

0

Looks like a typo: use initialize instead of initiate.

You state that you were using body onload="initialize()", and when you moved the call to your initialize function to a button's onclick it stopped working.

In your example however, you've used initiate:

<a href="javascript:;" style="center" onclick="initiate()" class="button">Get Geolocation data</a>

<input type="button" value="Get Geolocation Data" onclick="initiate()">
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
0

That is because you are using onlick on a anchor element without stopping its default behavior. Try this.

<a href="#" style="center" onclick="return initialize()" class="button">Get Geolocation</a>

And return false from initialize js method.

function initiate() {
   geocoder = new google.maps.Geocoder();
   return false;
}

As @Michael mentioned there is a typo as well.

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

Change this:

<a href="javascript:;" style="center" onclick="initiate()" class="button">Get Geolocation data</a>

To this:

<a href="javascript:initiate();return(false);" style="center" class="button">Get Geolocation data</a>

And make sure whether your function is called initiate() or initialize(). There seems to be a typo there.

Felipe Brahm
  • 3,162
  • 1
  • 28
  • 42