Sunday 12 January 2014

Google map(v3) into bootstrap modal-3.0

Having a Google-map into Bootstrap-3.0 Modal

"It is a given that any competent business landing-page should have a map"
This is a short description to help setup the google-map into a modal when using Bootstrap-3.0. I also use jQuery in the front end. Bootstrap uses jQuery by default, so in case you are using Bootstrap framework it is always to learn a beginner level of jQuery to make life easier!.

This is heavily "inspired" from Google's own tutorial and another better tutorial from Google.

The first step is to create a <div></div> which would house the map. Provide an id of your choice. For the tutorial purpose I named it "map_canvas".

Let us now place the <div> node into the modal under the <div class="modal-body">. So the html should look like:

 

Now get the styling elements for this ready in a .css file or inside html itself. The height and width of the element should be clearly defined. Defining a non-white color background is very useful during testing. So my CSS code would look like:

At this point, loading the html should give you a grey box. Now let us get into the fun part. Lets load the js file for the google map api's. From my little observation, i noticed this weird fact that the js file worked only when it is in the <head> node. Please add this to the head node.

To get the map displayed in the map canvas we need to call initialize the google.maps.Map function and to get a marker to show the location we need google.maps.Marker objects. For simplicity sake I enclosed both of them in a function named initialize. The list of options to control the Map can be accessed from this document.

This function needs to be called when the modal is being rendered. Bootstrap provides a neat little trigger in name of 'shown.bs.modal'. Combining the two the js code would look like:

We can find the necessary latitude and longitude from google maps from here. Now zoom in and out to find the zoom level you are comfortable presenting and there you go!. You should be seeing the maps in the modal as it pops up.

There are cases when the zoom-bar doesn't show up properly. This is due to the default 'max-width' attribute for the img and needs to be adjusted for the map_canvas. The final CSS:


Hope you are successful in embedding maps into your modals for a better user experience. I shall explore advanced aspects of displaying maps later on, but comments are welcome.
 

 

1 comment: