Adam
Adam

Reputation: 29119

load google maps on click

I want to show Google Map, after a link is clicked.

I have tried the following. When the link is clicked, then:

  1. Insert div after link with id map
  2. Load Google Maps API with jQuery method $.getScript
  3. Add Google Maps to div with id map

Unfortunately, step 2 does not seem to work. In the JS console I find the error

ReferenceError: google is not defined

This is my code, except that I have replaced my actual Google API key with the string mykey at the line

 $.getScript("https://maps.googleapis.com/maps/api/js?key=mykey");

Why cant I include the Google Maps API like this? How can I include it?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="/resources/vendor/jQUery/jquery-1.11.2.min.js"><\/script>')</script>
    <script>
    $(document).ready(function(){
      $('#showMap').click(function(e){
        e.preventDefault();

        $('#showMap').after("<div id='map' style='height: 200px;background-color:#08c;width: 200px;'></div>");

        $.getScript("https://maps.googleapis.com/maps/api/js?key=mykey");

        $lat   = 10.1364;
        $lng   = -80.2514;

        var myLatLng = {lat: $lat, lng: $lng};

          var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 11,
            center: myLatLng
          });

          var marker = new google.maps.Marker({
            position: myLatLng,
            map: map
          });
      });
    });
    </script>
  </head>
  <body>
    <a href='#' id="showMap">Hello</a>
  </body>
</html>

Upvotes: 0

Views: 4768

Answers (1)

j_d
j_d

Reputation: 3082

It works completely fine. Look at this fiddle. The problem is that you were doing all of your init stuff synchronously, whereas getScript is an async call for an external script.

The second argument of $.getScript takes a callback function.

Also, there's no need to add your map div after, just have it there in the first place.

$('#show-map').click(() => {
  $.getScript('https://maps.googleapis.com/maps/api/js', () => {

    var myLatLng = {
      lat: 10.1364,
      lng: -80.2514
    }

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 11,
      center: myLatLng
    })

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map
    })

  })
})

Upvotes: 5

Related Questions