谷歌地图API v3放置搜索 - 将另一个参数传递给回调函数

时间:2012-05-04 00:09:56

标签: javascript google-maps-api-3 callback

我正在使用Google Maps place 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);
    }
});

以下是回调函数,它们的区别仅在于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));
        }
    }
}

此代码100%工作,但我想避免为每个不同的地方类型重复回调(大约10个)。 有什么方法可以将标记网址传递给回调函数吗?那么我只需要一次回调...

1 个答案:

答案 0 :(得分: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
  }
}