Asynchronous loading of the Maps API is slightly more complicated than that, because although you have added the bootstrap library script to your page, you haven't waited until the maps module itself has loaded before attempting to start authentication.
1) Firstly you need to add the <script>
to to the header as you did in your code. Note that the URL has the additional blank=true
parameter so only the bootstrap is loaded.
function asyncLoadMapsLibrary() {
$.getScript('http://js.cit.api.here.com/se/2.5.4/jsl.js?blank=true',
hereMapLoaderCallback);
}
2) Then on the bootstrap callback you can decide which features you wish to load and initialize asynchronously using nokia.Features.load()
- onApiFeaturesLoaded()
is the callback from this callback.
function hereMapLoaderCallback() {
var fmatrix = nokia.Features.getFeaturesFromMatrix(['maps']),
// This callback is run if the feature load was successful.
onApiFeaturesLoaded = function () {
authenticate(HereMapsConstants.AppIdAndToken);
var map = createMap(
document.getElementById('mapContainer'));
map.addListener('displayready', function () {
afterHereMapLoad(map);
}, false);
},
// This callback is run if an error occurs during the feature loading
onApiFeaturesError = function (error) {
alert('Whoops! ' + error);
};
nokia.Features.load(
fmatrix,
onApiFeaturesLoaded, // an callback when everything was successfully loaded
onApiFeaturesError, // an error callback
null, // Indicates that the current document applies
false //Indicates that loading should be asynchronous
);
}
3) At this point you can do the authentication with your app_id
and app_code
. note that this particular example is using the CIT environment. Remove the line set('serviceMode', 'cit')
and amend the <script>
tag referenced in step 1 if you are using the live environment.
function authenticate(settings) {
// Add your own appId and token here
// sign in and register on http://developer.here.com
// and obtain your own developer's API key
nokia.Settings.set('app_id', 'YOUR_APPID');
nokia.Settings.set('app_code', 'YOUR_TOKEN');
// Use staging environment (remove the line for production environment)
nokia.Settings.set('serviceMode', 'cit');
// The language of the map can be changed here.
nokia.Settings.set('defaultLanguage', settings.language);
}
4) Now you can create the map
function createMap(domElement) {
var map = new nokia.maps.map.Display(domElement, {
center: [50.886944, 4.263056],
zoomLevel: 10, // Bigger numbers are closer in
components: [ // We use these components to make the map interactive
new nokia.maps.map.component.ZoomBar(),
new nokia.maps.map.component.Behavior()
]
});
return map;
}
5) And finally and only once the map is ready to display add the necessary content in a third callback
map.addListener('displayready', function () {
// Callback code goes here, add markers etc.
}
A working example can be found here