简体   繁体   English

Google Maps JavaScript API v3:多个地方的getDetails(请求,回调)

[英]Google Maps JavaScript API v3: getDetails(request, callback) for multiple places

I have implemented Google Maps JavaScript API v3 to contrive a custom store locator for my company's website. 我已经实现了Google Maps JavaScript API v3,以便为我公司的网站设计自定义商店定位器。 Let me start by saying that the code I have works for the two stores, but it would not be efficient or feasible if I added any more stores because of the "hacky" code used to make it work. 首先,我说我拥有的代码可用于这两个商店,但是如果我添加更多的商店,这将是无效或不可行的,因为它使用了“ hacky”代码。

I am using the Google Maps Places Library to send "place details" requests to Google using the getDetails() method. 我正在使用Google Maps Places Library通过getDetails()方法向Google发送“场所详细信息”请求。 On the callback, I am receiving the InfoWindow information (name, address, location) for each of my store locations. 在回调中,我收到每个商店位置的InfoWindow信息(名称,地址,位置)

I create a marker for each place, then use google.maps.event.addListener to coordinate the Place, Marker, and InfoWindow objects. 我为每个位置创建一个标记,然后使用google.maps.event.addListener协调Place,Marker和InfoWindow对象。 This is where I encounter problems. 这是我遇到问题的地方。 The place details requests are not always received in the same order they are sent which throws off the indexing of my buttons that have a data-marker attribute set to 0 and 1, respectively, to correlate to the map markers. 地点详细信息请求的接收顺序并不总是与发送顺序相同,这会使我的按钮的索引中断,这些按钮的data-marker属性分别设置为0和1,以与地图标记相关联。

Is there anyway to delay the second request until the first is finished? 无论如何,有没有将第二个请求延迟到第一个请求完成之前? or write the script in a way that maintains ordinal integrity? 还是以保持顺序完整性的方式编写脚本?

The first snippet of code below is my event handler to bind the click listener to each button using the .place.placeId property of the marker rather than the preferred technique of using the index of the markers array (the markers array holds the place details for the two stores). 下面的代码的第一个片段是我的事件处理程序,该事件处理程序使用marker的.place.placeId属性而不是使用markers数组的索引的首选技术 (将markers包含位置详细信息)click侦听器绑定到每个按钮两家商店)。

None of the demos or examples in the Google Maps API documentation (Places Library) delineate the procedure for multiple places. Google Maps API文档(位置库)中的所有演示或示例都没有描述多个位置的过程。 Any tips, resources, or suggestions will be much appreciated 任何提示,资源或建议将不胜感激

Website: http://m.alliancepointe.com/locate.html 网站: http//m.alliancepointe.com/locate.html

Event Handler 事件处理程序

 $(".loc-btn").on('click', function () {
        var me = $(this).data('marker');
        var place1 = markers[0].place.placeId;
        var myIndex = me == place1 ? 0 : 1;
        google.maps.event.trigger(markers[myIndex], 'click');
    }); 

Full JS 全JS

var markers = [];
var map;
var infowindow;
var service;

function initialize() {
    var index;
    var daddr;
    var idVA = 'ChIJKezXgqmxt4kRXrAnqIwIutA';
    var geoVA = '38.80407,-77.062881/Alliance+Pointe,+LLC';

    var idDC = 'ChIJDQlqOLG3t4kRqDU3uNoy4hs';
    var geoDC = '38.90188,-77.049161/Alliance+Pointe,+LLC';

    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        center: {lat: 38.90188, lng: -77.049161},
        zoom: 10,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
    };

    map = new google.maps.Map(document.getElementById('map'),
        mapOptions);

    var request = [
        {placeId: idVA, location: {lat: 38.80407, lng: -77.062881}},
        {placeId: idDC, location: {lat: 38.90188, lng: -77.049161}}
    ];

    var office = [
        "Main Office",
        "Principal Office"
    ];

    infowindow = new google.maps.InfoWindow();
    service = new google.maps.places.PlacesService(map);

    for (var i = 0; i < request.length; i++) {

        service.getDetails(request[i], function (placeResult, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                var id = placeResult.place_id;
                var location = placeResult.geometry.location;
                var trimAddr = placeResult.formatted_address.split(", ");

                var image = {
                    url: 'images/icons/AP-marker_large.png',
                    scaledSize: new google.maps.Size(32, 54)
                };
                var marker = new google.maps.Marker({
                    map: map,
                    place: {
                        placeId: id,
                        location: location
                    },
                    icon: image,
                    title: "Get directions"
                });

                google.maps.event.addListener(marker, 'click', function () {
                    if (id == idVA) {
                        index = 0;
                        daddr = geoVA;
                        trimAddr[0] = "1940 Duke St #200";
                    } else {
                        index = 1;
                        daddr = geoDC;
                        trimAddr[0] = "2200 Pennsylvannia Ave NW";
                    }
                    infowindow.setContent('<div class="info-window title">' + placeResult.name + "</div><div class='info-window sub-title'>" + office[index] + '</div><div class="info-window">' + trimAddr[0] + '<br>' + trimAddr[1] + ", " + trimAddr[2] + '</div><div class="info-window direction-div"><div class="direction-icon"></div><a class="google-link save-button-link" target="_blank" href="https://www.google.com/maps/dir/Current+Location/' + daddr + '">Get Directions</a></div>');
                    infowindow.open(map, marker);
                });

                markers.push(marker);
                //bounds.extend(location);
            }
        });
    }

    if (!bounds.isEmpty()) {
        map.fitBounds(bounds);
    }

    $(".loc-btn").on('click', function () {
        var me = $(this).data('marker');
        var place1 = markers[0].place.placeId;
        var myIndex = me == place1 ? 0 : 1;
        google.maps.event.trigger(markers[myIndex], 'click');

        //console.log("PlaceId = " + me);
        //console.log("Adj index = " + myIndex);
        //console.log("0:VA array index = " + markers[0].place.placeId);
        //console.log("1:DC array index = " + markers[1].place.placeId);
    });

    google.maps.event.addListenerOnce(map, 'idle', function () {
        $.mobile.loading("hide");
        $(".loc-btn").prop("disabled",false);
    });

}
google.maps.event.addDomListener(window, 'load', initialize);

HTML: Map & Buttons HTML:地图和按钮

<div data-role="content" class="full-width">

        <figure id="map"></figure>

        <div class="loc-btn-set">
            <button disabled data-role="none" data-theme="a" data-marker="ChIJKezXgqmxt4kRXrAnqIwIutA" class="loc-btn nightly-button">VA <span>- Alexandria</span></button>
            <button disabled data-role="none" data-theme="b" data-marker="ChIJDQlqOLG3t4kRqDU3uNoy4hs" class="loc-btn nightly-button">DC <span>- Washington</span></button>
        </div>
    </div>

The simpliest approach based on the given code would be to add the click-handler for the buttons inside the getDetails -callback. 基于给定代码的最简单方法是在getDetails内部添加按钮的单击处理程序。

Add this after the creation of the marker : 在创建marker后添加以下内容:

            $('.loc-btn[data-marker="'+id+'"]').click(function(){
              google.maps.event.trigger(marker,'click');
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对Google Maps v3 API getDetails()函数感到困惑 - Confused about Google Maps v3 API getDetails() function 谷歌地图API v3放置搜索 - 将另一个参数传递给回调函数 - Google maps API v3 places search - pass in another parameter to callback function 在Google Maps Javascript API v3中一次拖动多个多边形 - Drag multiple polygons at once in Google Maps Javascript API v3 Google Maps JavaScript API v3-在iPhone上查看的网页上的自动填充字段不存储值,不返回任何位置 - Google Maps JavaScript API v3 - Autocomplete fields on webpage viewed on iPhone do not store a value, returns no places 谷歌地图javascript api v3地方库不会返回任何结果的边界 - google maps javascript api v3 places library doesn't return any results for the bounds 样式的地图和地方资料库Google Map API v3 - styled maps and places library Google Map API v3 Google Maps Javascript API V3无法正常工作 - Google Maps Javascript API V3 not working Google Maps API v3出现问题-Javascript - Trouble with Google Maps API v3 - Javascript 是否可以在 google maps api v3 中添加个人地点以自动完成? - Is possible add personal places to autocomplete in google maps api v3? Google Maps API V3 - 最接近边界内的路线 - Google Maps API V3 - Closest places to route within boundary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM