简体   繁体   中英

jQuery Document Ready Function Syntax with Google Maps API

I am trying to add the google geocode service to a webpage and am having some JavaScript trouble. When I add the below code without jQuery, I receive the null reference error, but can still occasionally get the service to work. Based on what I'm reading, it is the JS running before the element has loaded and I can wrap this JS into a jQuery function to resolve the issue. However, when I add my code as below, this is error is still popping up and I cannot get the service to run at all. Is there something incorrect in my jQuery syntax? I am very new to JS. Thanks.

"JavaScript runtime error: Unable to get property 'addListener' of undefined or null reference"

<script type="text/javascript">
    $(document).ready(function(){
        google.maps.event.addDomListener(window, 'load', initialize);
        function initialize() {
            var autocomplete = new google.maps.places.Autocomplete(document.getElementById('PostalCodeID'));
            google.maps.evenet.addListener(autocomplete, 'place_changed', function () {
                var places = autocomplete.getplace();
                var location = "<b>Location:</b>" + places.formatted_address + "<br/>";
                location += "<b>Latitude:</b>" + places.geometry.location.A + "<br/>";
                location += "<b>Longitude:</b>" + places.geometry.location.F + "<br/>";
                document.getElementById('lblresult').innerHTML = location
            });
        };
        });

</script>

As Pointy "pointed out" (sorry, couldn't help myself), you are using both an onLoad and an onReady handler. Either one (but certainly the onReady) would handle any sort of "page hasn't loaded its contents yet" issues. But, despite having both, you are still getting errors.

One likely culprit (also pointed out by Pounty) is your misspelling of event as evenet . If you still get errors after fixing that then you likely have some other element which is missing when your code triggers. The most likely culprit I see for that is your element with an ID "PostalCodeID".

There are also things you can do to help narrow down the problem. For instance, the stack trace of your error should include a pointer to a line of your code; if you look at which line that is it should help to determine what you're trying to do that the browser doesn't think is possible.

Once you find the line that is causing the problem, you can add a debugger statement just before it and then use your browser's debugger to see what's going on. You can also run code like document.getElementById('PostalCodeID') to confirm that the element really is/isn't on the page at that point in time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM