我正在尝试使用javascript Maps API。我开始创建一个小网页,调用API来显示地图并添加标准标记。工作得很好。现在我想在SharePoint中使用它,使用JSLink进行列表。所以我在SharePoint上提供了JQuery,并写了这样的东西:
$.getScript("http://js.cit.api.here.com/se/2.5.3/jsl.js?with=maps", function () {
nokia.Settings.set("app_id", "MY APP ID");
nokia.Settings.set("app_code", "MY APP CODE");
// Use staging environment (remove the line for production environment)
nokia.Settings.set("serviceMode", "cit");
var mapContainer = document.getElementById("mapContainer");
var map = new nokia.maps.map.Display(mapContainer, {
// initial center and zoom level of the map - Around U2U.
center: [50.886944, 4.263056],
zoomLevel: 10
});
});
nokia.maps.map在这里返回undefined。在普通代码块中使用它,带有用于引用api的脚本标记可以正常工作。怎么了?
答案 0 :(得分:1)
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 <的回调/ strong>回调。
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环境。如果您使用的是实时环境,请删除行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