King Kong
King Kong

Reputation: 2915

How to embed google map?

I am trying to add a Google Map to my website, and I tried this:

 $.getScript("https://maps.googleapis.com/maps/api/js?sensor=false", function () {
     alert("1");          
     var map;
     var myOptions = {
         zoom: 8,
         center: new google.maps.LatLng(-34.397, 150.644),
         mapTypeId: google.maps.MapTypeId.ROADMAP
     };
     alert("2");
     map = new google.maps.Map(document.getElementById("container"), myOptions);
 });

This is not working. Can anybody tell me why?

EDIT

Script loaded perfectly. I know this because alert(1) shows but after that control does not reach alert(2).

Upvotes: 0

Views: 619

Answers (3)

Rifat
Rifat

Reputation: 7718

You have to use async loading for this - https://developers.google.com/maps/documentation/javascript/tutorial#asynch

In the current approach, the script do this-

function getScript(src) {
  document.write('<' + 'script src="' + src + '"' + ' type="text/javascript"><' + '/script>');
}

So, when you call $.getScript, that will goto void. And, google.maps.LatLng becomes undefined.

I've created a version with the async one. You can check the fiddle @ http://jsfiddle.net/rifat/G3yPw/

Upvotes: 1

duncan
duncan

Reputation: 31912

document.getElementById(id)

What is id, where did that get defined?

Also getScript is for doing Ajax requests, which isn't really how you should be doing Google Maps. Just call the script in the normal way, and have an init function which executes on document ready. Or even better use the window.load event listener that the Google Maps API provides for you anyway.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false" />

<script type="text/javascript">
function init(id) 
     {          
             var map;
             var myOptions = {
                 zoom: 8,
                 center: new google.maps.LatLng(-34.397, 150.644),
                 mapTypeId: google.maps.MapTypeId.ROADMAP
             };
             map = new google.maps.Map(document.getElementById(id), myOptions);
     }

google.maps.event.addDomListener(window, 'load', init('yourDivID'));
</script>

Upvotes: 4

zessx
zessx

Reputation: 68790

You should have a look on your container div.

It must have specified width and height.

And I used to separate the affectation of LatLng :

     var map;
     var ll = new google.maps.LatLng(-34.397, 150.644);
     var myOptions = {
         zoom: 8,
         center: ll,
         mapTypeId: google.maps.MapTypeId.ROADMAP
     };
     map = new google.maps.Map(document.getElementById("container"), myOptions);

Upvotes: 0

Related Questions