整体图片:
我想在我的应用程序中添加地理编码。我能够直接使用JavaScript,但转换为Angular / TypeScript后回调不会被触发。
示例:如果用户输入 1 Microsoft Way,Redmond,WA 。经度和纬度应返回:纬度:47.64006815850735,经度:-122.12985791265965
代码示例基于以下资源构建:
错误详细信息:
错误发生在变量名称中:geocodeRequest
。 searchModuleLoaded()
已加载,但我的geocodeRequest
永远不会触发geocodeCallback
或errCallback
。我认为它与我的方法的范围有关,但似乎无法隔离导致错误的原因。关于如何触发我的回调的任何想法?
Angular / TypeScript(不工作)
$onInit() {
this.getMap();
}
getMap() {
this.map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: "your key here"});
Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback: this.searchModuleLoaded });
};
searchModuleLoaded() {
var searchManager = new Microsoft.Maps.Search.SearchManager(this.map);
var geocodeRequest = {
where: "1 Microsoft Way, Redmond, WA",
count: 10,
callback: this.geocodeCallback,
errorCallback: this.errCallback
};
searchManager.geocode(geocodeRequest);
}
geocodeCallback(geocodeResult, userData) {
// this callback never gets triggered
alert("The first geocode result is " + geocodeResult.results[0].location + ".");
}
errCallback(geocodeRequest) {
// this callback never gets triggered
alert("An error occurred.");
}
工作版本(Works,但没有Angular / TypeScript)
function GetMap(){
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials: "key goes here", center: new Microsoft.Maps.Location(47.5, -122.3), zoom: 9 });
Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback: searchModuleLoaded });
}
function searchModuleLoaded(){
var searchManager = new Microsoft.Maps.Search.SearchManager(map);
var geocodeRequest = {where:"1 Microsoft Way, Redmond, WA", count:10, callback:geocodeCallback, errorCallback:errCallback};
searchManager.geocode(geocodeRequest);
debugger;
}
function geocodeCallback(geocodeResult, userData){
alert("The first geocode result is " + geocodeResult.results[0].location + ".");
}
function errCallback(geocodeRequest){
alert("An error occurred.");
}
答案 0 :(得分:0)
在进一步调查后,我能够解决我的问题。
问题是什么?
问题发生在searchModuleLoaded
内。两个回调都是undefined
。一个问题是它在模块加载之前尝试执行searchModuleLoaded
而导致另一个问题,因为它不知道this
的上下文。
要解决此问题,我必须在加载Microsoft.Maps.Search
时修改回调。模块的回调现在转换为lambda函数,调用this.searchModuleLoaded()
。一旦将其编译为JavaScript,它就会设置this
上下文,即_this = this
。我的代码现在看起来像这样:
getMap() {
this.map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: "put your key here"});
Microsoft.Maps.loadModule('Microsoft.Maps.Search', {
callback: () => {
this.searchModuleLoaded();
}
});
};
searchModuleLoaded() {
var searchManager = new Microsoft.Maps.Search.SearchManager(this.map);
var geocodeRequest = {
where: "1 Microsoft Way, Redmond, WA",
count: 10,
callback: this.geocodeCallback,
errorCallback: this.errCallback
};
searchManager.geocode(geocodeRequest);
};
geocodeCallback(geocodeResult, userData) {
alert("The first geocode result is " + geocodeResult.results[0].location + ".");
};
errCallback(geocodeRequest) {
alert("An error occurred.");
};