mheavers
mheavers

Reputation: 30158

mapbox.js - can't initialize map unless it is available in global scope

I'm trying to use mapbox within a module pattern javascript project I've set up. The same code that worked in a prototype when I made all my variables accessible to the global scope is not working when I try to initialize mapbox within my module pattern. In other words, before I had this:

<html>
  <head>
  <script="js/mapbox.js"></script>
  </head>
  <body>
  <div id="map"></div>
  <script>
    L.mapbox.accessToken = '[access_token]';
    var map = L.mapbox.map('map','heaversm.b8aa0d0a')
  </script>
  </body>
</html>

Which worked. And now what I have is this:

<html>
  <head>
  <script="js/mapbox.js"></script>
  </head>
  <body>
  <div id="map"></div>
  <script src="js/main.js></script>
  <script="js/map.js"></script>
  </body>
</html>


//main.js:

var synBio = {};
var synBioModule;
synBio.main = function() {
  self.mapModule = new synBio.map();
  self.mapModule.init();
}

$(document).ready(function(){
    synBioModule= new synBio.main();
    synBioModule.init();
});

//map.js

synBio.map = function(){
  L.mapbox.accessToken = '[access_token]';
  var self = this;
  var map;
  self.init = function(){
    map = L.mapbox.map('map','heaversm.b8aa0d0a')
  }
}

But when I do this I get a 404 error when trying to load the tiles:

http://a.tiles.mapbox.com/v4/heaversm.ac964855.json?access_token=[access_token]

Everything seems to be loading in the proper order, so I don't get what's wrong. I've tried to do an onready event for the tile layer before initializing the map:

mapTiles = L.mapbox.tileLayer('heaversm.ac964855').on('ready',initializeMap);

var initializeMap = function(){
  map = L.mapbox.map('map','heaversm.b8aa0d0a')
}

Any ideas what I need to do to get this working again?

Upvotes: 0

Views: 739

Answers (1)

iH8
iH8

Reputation: 28638

First off, couple of things are wrong with your code: <script="js/map.js"></script> should be <script src="js/map.js"></script>. Which should give you:

Uncaught ReferenceError: L is not defined

Next you're calling the init method of synBioModule in your onready eventhandler but synbioModule is an instance synBio.main, which has no init method. That should render you a:

Uncaught TypeError: synBioModule.init is not a function

I'm guessing they're just typo's or c/p errors when posting the code here because they don't correspond with the error you are getting. I have corrected these mistakes in the following example: http://plnkr.co/edit/Or8fLh?p=preview using my own public token plus project id and your code just works™.

When i use an invalid project id i get the following errors:

GET http://a.tiles.mapbox.com/v4/INVALID_PROJECT_ID?access_token=VALID_PUBLIC_TOKEN 404 (Not Found)

could not load TileJSON at http://a.tiles.mapbox.com/v4/INVALID_PROJECT_ID.json?access_token=VALID_PUBLIC_TOKEN

You must be using an invalid project id.

Upvotes: 1

Related Questions