谷歌地图,将“地图”传递给另一个事件

时间:2015-06-18 22:52:43

标签: javascript google-maps google-maps-api-3

我有2个不同的事件,如果我做错了,请纠正我,

    //initializing the map
    google.maps.event.addDomListener(window, 'load', initialize);

    //initializing the markers
    google.maps.event.addListener(map, 'idle', showMarkers);

第一个事件是初始化地图(设置它),第二个事件是当当前地图边界发生变化时查询数据库中的新标记(尚未发挥作用)

由于我在initialize函数中定义了“map”,如何在函数外部访问它并将其传递给第二个事件?正如你所看到的,我已经在函数之前将它声明为全局变量,但它仍然未定义为事件参数,我已经被困在这几天

var map;
function initialize(){
        //defining map options
        var mapLatlng = new google.maps.LatLng(37.09024, -100.712891);
        var mapOptions = {
            zoom: 4,
            center: mapLatlng
        }
        //defining the map itself
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    }

    function showMarkers(){

        Parse.initialize("X","X");

        var query = new Parse.Query("business_and_reviews");
        var results = new Parse.Object("business_and_reviews");

        query.equalTo("name","McDonalds");

        query.find({
            success: function(results) {
                console.log(results);

                for (var i = 0; i < results.length; i++) {
                    var object = results[i];
                }

                var lat = (object["attributes"]["lat"]);
                var lng = (object["attributes"]["lng"]);

                console.log(lat);
                console.log(lng);

                //adding the marker from the query
                var marker = new google.maps.Marker({
                    position: mapLatlong,
                    map: map,
                    title: 'Hello World!'
                });

            },
            error: function(object, error) {
            }
        });

    }
    //initializing the map
    google.maps.event.addDomListener(window, 'load', initialize);

    //initializing the markers
    google.maps.event.addListener(map, 'idle', showMarkers);

对于第二个事件,“地图”未定义

1 个答案:

答案 0 :(得分:0)

做到了!将idle事件监听器放在initialize函数中,它就像一个魅力!我想initilize不是最初初始化页面而是经常运行