HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Placing a Google map in Colorbox

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mapplacingcolorboxgoogle

Problem

I need to place a Google map in Colorbox overlay and am wondering if there's a better way to do this. I've just started out with Google's tutorial so there's nothing fancy going on.

Right now I'm hiding the div that Google loads the map into:


    


Here's the call to Colorbox:

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

$(document).ready(function(){

    $("#farm_on_google_maps").colorbox({
        inline: true,
        width:700,
        height:450,
        href : '#map_canvas'
        });
});


Even though it works, I wonder if the map could be loaded directly into Colorbox.

Solution

If you want to dynamically insert the Google Map, instead of simply linking to an href, you can do as follows:

In your HTML, have the basic outline for the colorbox ready:


    


Then, when you invoke your colorbox, invoke it with an html option:

$("#farm_on_google_maps").colorbox({
            inline: true,
            width:700,
            height:450,
            html : $("#box").html()
            });


This will setup your colorbox with the basic HTML structure. We then want to insert the google map dynamically into the colorbox as follows:

var googleMap = $("#cboxLoadedContent").find("div.google-map")[0];
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(googleMap, myOptions);


The cboxLoadedContent div is created by the colorbox when it's invoked, so it's simply a matter of grabbing that, and using it to setup the Google Map.

Code Snippets

<div id="box">
    <div class="google-map"></div>
</div>
$("#farm_on_google_maps").colorbox({
            inline: true,
            width:700,
            height:450,
            html : $("#box").html()
            });
var googleMap = $("#cboxLoadedContent").find("div.google-map")[0];
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(googleMap, myOptions);

Context

StackExchange Code Review Q#1223, answer score: 4

Revisions (0)

No revisions yet.