Maps API 的异步加载比这稍微复杂一些,因为尽管您已将引导库脚本添加到您的页面,但您并没有等到地图模块本身加载完毕后才尝试开始身份验证。
1) 首先,您需要像在代码中那样将<script> 添加到标题中。请注意,该 URL 具有额外的 blank=true 参数,因此仅加载引导程序。
function asyncLoadMapsLibrary() {
$.getScript('http://js.cit.api.here.com/se/2.5.4/jsl.js?blank=true',
hereMapLoaderCallback);
}
2) 然后在引导回调中,您可以使用 nokia.Features.load() 决定您希望异步加载和初始化哪些功能 - onApiFeaturesLoaded() 是来自 this 回调的回调.
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) 此时您可以使用app_id 和app_code 进行身份验证。请注意,此特定示例使用的是 CIT 环境。如果您使用的是 live 环境,请删除 set('serviceMode', 'cit') 行并修改步骤 1 中引用的 <script> 标记。
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)现在您可以创建地图了
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)最后也是只有地图准备好显示在第三个回调中添加必要的内容
map.addListener('displayready', function () {
// Callback code goes here, add markers etc.
}
可以在here找到一个工作示例