Search code examples
jquerygoogle-maps-api-3jquery-ui-mapinfobox

How to target a jquery-ui-map generated map when using InfoBox


I'm using jquery-ui-map to create a Google Maps instance like this:

$('#CHMap').gmap({
  mapTypeControl : false
}).bind('init', function(evt, map) {
  log("Map initilised");
});

Then elsewhere in script I'm using InfoBox to add some style-able info boxes filled with data pulled back from from a geolocation service like so:

var boxText = document.createElement("div");
var ib = new InfoBox(myOptions); //myOptions can be ignored for this example

$.each(data, function(name, value) {
  $('#CHMap').gmap('addMarker', {
    id:value['YourId'],
    'position': value['Latitude']+','+value['Longitude'],
    'bounds': true,
    'icon': '/img/gicon.png'
  }).click(function() {
    boxText.innerHTML = "hello";
    ib.setContent(boxText);
    ib.open(map, this);
  });
});

'data' is an object returned from the Geolocation service. If I place the above 'addMarker' code inside the bound 'init' function when the gmap is first created, the infoBox displays fine. When I use the 'addMarker' code elsewhere, I get "Uncaught ReferenceError: map is not defined" error in console.

How can I reference the 'map' correctly? It looks like I cannot do var map = $('#CHMap').gmap({//options}); as the 'jquery-ui-map' docs suggest that gmap returns nothing.


Solution

  • I think you can do

    var map = $('#CHMap').gmap();
    

    Note from OP. The correct way in the latest plugin is:

    var map = $('#CHMap').gmap('get', 'map');
    

    I don't see where it's saying it returns nothing in the API

    when you need to run access the map you can add the code inside a google maps event listener that waits until the map tiles are loaded like this.

    As Gmaps is fetched async from google you cannot always be sure it will be there when you call it unless you do something like this.

    google.maps.event.addListener(YOUR_GOOGLE_MAPS_INSTACE, 'tilesloaded', function() {
           // put your initialization code in here.
    }
    

    So it will only execute after the maps is completely loaded.

    Cheers from Brazil !