javascript - Google maps API v3 places search - 将另一个参数传递给回调函数

标签 javascript google-maps-api-3 callback

我正在使用 Google Maps places API v3 返回许多“类型”的地点,每个地点由 map 上的不同标记表示。

我创建了一个 google.maps.places.PlacesService 对象,然后针对每个地点类型调用一次“搜索”方法。每次我都使用不同的回调函数(“search”的第二个参数),因为我需要为每种类型选择不同的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 个)。 有什么方法可以将标记 URL 传递给回调函数吗?那么我只需要一个回调...

最佳答案

以下情况如何:

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
  }
}

关于javascript - Google maps API v3 places search - 将另一个参数传递给回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10441038/

相关文章:

javascript - 隐藏表行未显示正确信息

javascript - Angularjs watch 未触发

python - 当某些项目相互依赖时,如何运行异步进程列表?

javascript - 如何在多系列 Highcharts 中显示固定的工具提示位置?

javascript - jquery 将数字转为数组

javascript - 我可以在 Google map 数据层中设置笔划样式吗?

javascript - 是否可以删除 RouteBoxer-boxes 的边框?

javascript - 将对象作为参数发送到回调函数-nodejs

javascript - 回调函数不执行