how*_*lee 10 javascript callback google-maps-api-3
我使用谷歌地图放置API v3来返回许多"类型"的地方,每个地点都由地图上的不同标记表示.
我创建了一个google.maps.places.PlacesService对象,然后按地点类型调用"搜索"方法一次.每次,我使用不同的回调函数("搜索"的第二个参数),因为我需要为每种类型选择不同的MarkerImage.
var address = "97-99 Bathurst Street, Sydney, 2000";
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
map.setCenter(location);
var marker = new google.maps.Marker({
map: map,
position: location
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
// banks
var req_bank = { location: location, radius: 500, types: ['bank'] };
service.search(req_bank, banks);
// bars
var req_bar = { location: location, radius: 500, types: ['bar'] };
service.search(req_bar, bars);
// car parks
var req_parking = { location: location, radius: 500, types: ['parking'] };
service.search(req_parking, carparks);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
Run Code Online (Sandbox Code Playgroud)
以下是回调函数,它们仅由MarkerImage区分:
function banks(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i], new google.maps.MarkerImage("/images/bank.png", null, null));
}
}
}
function bars(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i], new google.maps.MarkerImage("/images/bar.png", null, null));
}
}
}
function carparks(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i], new google.maps.MarkerImage("/images/parking.png", null, null));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码100%工作,但我想避免重复每个不同地方类型的回调(大约10个).有什么办法可以将标记URL传递给回调函数吗?然后我只需要一个回调......
Sco*_*ttE 11
以下内容如何:
service.search(req_bank, function (results, status) {
locations(results, status, "bank");
});
function locations(results, status, type) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// check the type to determine the marker, or pass a url to the marker icon
}
}
Run Code Online (Sandbox Code Playgroud)