Get Current Location If Checkbox Checked

311 views Asked by At

Hey everyone I have a geolocation script to get a visitors city and state. I am trying to run this script if the user selects to use this automatic feature. If the script is set to document ready then it works, but everytime I add a click feature it doesn't work. What am I doing wrong?

js

<script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCeLzjWfDaqBze8j7qKJL17XH4ZsMjsTx0&sensor=true">
</script>
<script>
$("#useLocation").click(function(){
    //I'm not doing anything else, so just leave
    if(!navigator.geolocation) return;

    navigator.geolocation.getCurrentPosition(function(pos) {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude);
        geocoder.geocode({'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                //Check result 0
                var result = results[0];
                //look for locality tag and administrative_area_level_1
                var city = "";
                var state = "";
                for(var i=0, len=result.address_components.length; i<len; i++) {
                    var ac = result.address_components[i];
                    if(ac.types.indexOf("locality") >= 0) city = ac.long_name;
                    if(ac.types.indexOf("administrative_area_level_1") >= 0) state = ac.long_name;
                }
                //only report if we got Good Stuff
                if(city != '' && state != '') {
                    $("#locationText").val(city+", "+state);
                }

            } 
        });

    });
    });

</script>

html

 <li><label for="cLocation">Use Current Location?</label> <input type="checkbox" id="useLocation" name="cLocation"> Yes</li>
<li><label for="dLocation">Where Will You Be:</label> <input type="text" name="dLocation" class="shortInput" id="locationText"></li>

There is nothing in my JS console about this not working, so I'm not sure why it's not. It just does nothing.

Can anyone help ?

1

There are 1 answers

2
jthomas On BEST ANSWER

Does the javascript appear after the checkbox in the markup? You may be trying to attach the handler before the element exists.