简体   繁体   English

如何在Google Maps v3 API上异步添加标记?

[英]How to add Markers on Google maps v3 API asynchronously?

I've been following the official documentation on how to add markers on the map so far 到目前为止,我一直在关注如何在地图上添加标记官方文档

Nevertheless, I can see only one marker at a time max. 不过,我一次最多只能看到一个标记。 If I try to add another one, then it doesn't work (I can't even see the first one). 如果我尝试添加另一个,那么它将不起作用(我什至看不到第一个)。 My process is the following: 我的过程如下:

I initialize gmaps api: 我初始化gmaps api:

    jQuery(window).ready(function(){ 
        //If we click on Find me Lakes
        jQuery("#btnInit").click(initiate_geolocation);
    });

    function initiate_geolocation() {  
        if (navigator.geolocation)  
        {  
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBbfJJVh0jL1X9b7XFDcPuV7nHD1HlfsKs&sensor=true&callback=initialize";
            document.body.appendChild(script);

            navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
        }  
        else  
        {  
            yqlgeo.get('visitor', normalize_yql_response);
        }  
    }

Then, I display it on the appropriate div. 然后,将其显示在适当的div上。 But when it comes to make the AJAX call, in order to get my locations of the different markers I'd like to display, It just doesn't work properly. 但是,当进行AJAX调用时,为了获取我想显示的不同标记的位置,它就无法正常工作。 Here is the code with a simple map displayed (since that's the only thing working for me so far). 这是显示了简单地图的代码(因为到目前为止这对我来说是唯一的工作)。

    function handle_geolocation_query(position){ 

        var mapOptions = {
            zoom: 14,
            center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
            mapTypeId: google.maps.MapTypeId.SATELLITE
          }

        alert('Lat: ' + position.coords.latitude + ' ' +  
              'Lon: ' + position.coords.longitude);

        $('#map-canvas').slideToggle('slow', function(){
            var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        });

        $.when( getLakes(position.coords.latitude, position.coords.longitude)).done(function(results) {
            // InitializeGoogleMaps(results);
            if(results)
            var data = results.map(function (lake) {
                //Check if the lake has any open swims, if not, the button will not be clickable and an alert will pop up
                if (lake.available>0)
                    clickable=true;
                else
                    clickable=false;

                    return {
                        name: lake.name,
                        fishs: lake.fisheryType,
                        swims: lake.swims,
                        dist: lake.distance,
                        lat: lake.latitude,
                        long: lake.longitude,
                        id: lake.id,
                        avail: lake.available,
                        clickable: clickable,
                        route: Routing.generate('lake_display', { id:  lake.id, lat: position.coords.latitude, lng: position.coords.longitude})
                    }
                });

            var template = Handlebars.compile( $('#template').html() );
            $('#list').append( template(data) );


        } );
    };

So I'd like to add markers after the AJAX call. 因此,我想在AJAX调用后添加标记。 I've set up a function that I should call in the when() 我已经建立了一个函数,应该在when()中调用

function InitializeGoogleMaps(results) {

};

to display the markers in a foreach loop but nope, can't make it work. 在foreach循环中显示标记,但不能,不能使其工作。 It looks like this : 看起来像这样:

CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
marker = new google.maps.Marker({
    position: location,
    map: map
});

Any help would be great ! 任何帮助都会很棒!

Thanks 谢谢

The main issue is that the map variable is declared only in the scope of the anonymous callback on slideToggle. 主要问题是map变量仅在slideToggle上的匿名回调的范围内声明。 First of all declare at the top-level function scope. 首先在顶层函数范围内声明。

function handle_geolocation_query(position){ 

    var map,
        mapOptions = {
            zoom: 14,
            center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
            mapTypeId: google.maps.MapTypeId.SATELLITE
        }
    ...

Then change the slideToggle callback to initialise the variable instead of redeclaring: 然后更改slideToggle回调以初始化变量,而不是重新声明:

$('#map-canvas').slideToggle('slow', function(){
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});

Then you should pass map as a second parameter to your InitializeGoogleMaps function and call it using InitializeGoogleMaps(results, map) . 然后,您应该将map作为第二个参数传递给InitializeGoogleMaps函数,并使用InitializeGoogleMaps(results, map)对其进行调用。 See where this gets you and hit me back with any questions. 看看这能帮到您,并向我提出任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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