简体   繁体   中英

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:

    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. 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. 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. I've set up a function that I should call in the when()

function InitializeGoogleMaps(results) {

};

to display the markers in a foreach loop but nope, can't make it work. 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. 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:

$('#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) . See where this gets you and hit me back with any questions.

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