从Bing Maps V8开始使用此示例
此行开始地图搜索:geocodeQuery("New York, NY");
此代码片段包含回调函数(将图钉放置在地图上:]
var searchRequest = {
where: query,
callback: function (r) {
//Add the first result to the map and zoom into it.
if (r && r.results && r.results.length > 0) {
var pin = new Microsoft.Maps.Pushpin(r.results[0].location);
map.entities.push(pin);
map.setView({ bounds: r.results[0].bestView });
}
},
errorCallback: function (e) {
//If there is an error, alert the user about it.
alert("No results found.");
}
};
如果我想执行多个搜索,我可以写:
geocodeQuery("New York, NY");
geocodeQuery("Queens, NY");
现在我在地图上有2个图钉。
下一步:如果我想标记引脚,则将扩展“新图钉代码”:
var pin = new Microsoft.Maps.Pushpin(r.results[0].location,
{
title: 'Queens',
text: '2'
});
问题:
引脚由回调函数放置。由于我希望每个针脚都有不同的文本,因此如何调整此示例代码,以便可以将新参数传递给回调函数?
您需要在geocodeQuery
函数中添加一个参数(可能称为title
),并在回调中创建引脚时使用该参数。然后,您只需调用geocodeQuery("Queens, NY", "Queens")
function geocodeQuery(query, title) {
//If search manager is not defined, load the search module.
if (!searchManager) {
//Create an instance of the search manager and call the geocodeQuery function again.
Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
searchManager = new Microsoft.Maps.Search.SearchManager(map);
geocodeQuery(query, title);
});
} else {
var searchRequest = {
where: query,
callback: function (r) {
//Add the first result to the map and zoom into it.
if (r && r.results && r.results.length > 0) {
var pin = new Microsoft.Maps.Pushpin(r.results[0].location, {
title: title,
text: '2'
});
map.entities.push(pin);
map.setView({ bounds: r.results[0].bestView });
}
},
errorCallback: function (e) {
//If there is an error, alert the user about it.
alert("No results found.");
}
};
//Make the geocode request.
searchManager.geocode(searchRequest);
}
}