Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - jquery: how can i load the Google Maps API via ajax?

Before you reply: this is not as straight foward as you'd expect!

  • I have a 'show on map' button which when clicked opens a dialogbox/lightbox with the google map in.
  • I don't want to load the maps api on pageload, just when a map has been requested

This is php file the "show on map" button puts into the dialog box:

<div id="map_canvas"></div>

<script type="text/javascript">
    $(function() {  
            //google maps stuff             
            var latlng = new google.maps.LatLng(<?php echo $coords ?>);
            var options = {
              zoom: 14,
              center: latlng,
              mapTypeControl: false,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };          
            var map = new google.maps.Map(document.getElementById('map_canvas'), options);          
            var marker = new google.maps.Marker({
              position: new google.maps.LatLng(<?php echo $coords ?>),
              map: map
            });
    })
</script>

I've been trying to load the API before ajaxing in the dialog like this:

$('img.map').click(function(){      
    var rel = $(this).attr('rel');
    $.getScript('http://maps.google.com/maps/api/js?sensor=false', function(){
        $.fn.colorbox({
            href:rel
        })
    });
})

this doesn't seem to work :(

i've also tried:

  • adding <script src="http://maps.google.com/maps/api/js?sensor=false"></script> to the ajax file
  • type="text/javascript" running $.getScript('http://maps.google.com/maps/api/js?sensor=false'); on doc.ready

the problem the browser seems to be redirected to the api.js file - you see a white screen

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This FAQ answer details how to load the Maps API asynchronously, and there is a good example that goes along with it.

Basically, recommend you put your execution code in a named function, then load the Maps API referencing said callback and using the "async" parameter. Or you could use jQuery's getJSON as such:

$.getJSON('http://maps.google.com/maps/api/js?sensor=false&async=2&callback=?', function(){
    $.colorbox({
        href:rel
    })
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...