简体   繁体   中英

calling ajax function that is outside document.ready

I am trying to populate a Google Map. Here's some of my code. Why won't this ajax request work? It works fine when I stick it all in the document.ready() as an anonymous function, but I want to reuse this code, so I need to be able to call it.

$(document).ready(function(){

    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 49.105, lng: -97.568},
        zoom: 4
      });

getTornadoes("test", "test", "yes");            

});

// Get the tornado JSON file
    function getTornadoes (test, test2, test3) {//These are not my real parameters

        $.getJSON('water_pollutants.php', function(data){

            $.each(data.features, function(index, feature){

                var longitude = feature.properties.LONGITUDE;
                var latitude = feature.properties.LATITUDE;
                ...

I get the error InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama. However, I don't think this is an issue with Google Maps. I've had similar issues in the past when trying to refer to ajax functions that are declared outside document.ready().

I use google maps api also, here is one recommendation:

change

$(document).ready(function(){

      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 49.105, lng: -97.568},
        zoom: 4
      });

to:

var map;

$(document).ready(function(){

      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 49.105, lng: -97.568},
        zoom: 4
      });

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