【问题标题】:Google maps API v3 places search - pass in another parameter to callback functionGoogle maps API v3 地点搜索 - 将另一个参数传递给回调函数
【发布时间】:2012-05-04 09:00:39
【问题描述】:

我正在使用 Google Maps Places 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 个)。 有什么方法可以将标记 URL 传递给回调函数吗? 那么我只需要一个回调...

【问题讨论】:

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


    【解决方案1】:

    以下内容如何:

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

    【讨论】:

    • 太棒了...正是我所追求的:)
    • 多伊!我应该知道的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2011-09-21
    • 2012-09-25
    • 2020-10-03
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多