如何为Google Maps正确格式化此JavaScript数组/对象?

时间:2016-02-08 10:31:57

标签: javascript arrays json google-maps object

在构建来自AJAX请求的数据方面遇到Google Maps API问题。这就是我现在所处的位置:

const getMarkerData = function ( googlemap, $hook ) {
const hData = $hook.dataset;
const format = "json";
const dataType = "json";
const markerData = [];
let item = null;

core.api.collection( hData.url, format, dataType ).done(( response ) => {
    const items = response.items;

    if ( response.items ) {
        let i = items.length;

        for ( i; i--; ) {
            item = items[ i ];
            markerData.push({
                position: new google.maps.LatLng(item.location.mapLat, item.location.mapLng),
                title: item.location.addressTitle
            });
        }
    }
    const googleMapMarkers = new google.maps.Marker( markerData );

    googleMapMarkers.setMap( googlemap );
});
};

根据我的理解,Google地图需要JSON中的数据,而不是数组中的数据。我可以调整什么来获得它?

新修订的工作代码:

core.api.collection( hData.url, format, dataType ).done(( response ) => {
    const items = response.items;

    if ( response.items ) {
        let i = items.length;

        for ( i; i--; ) {
            item = items[ i ];

            marker = new google.maps.Marker({
                position: new google.maps.LatLng(item.location.mapLat, item.location.mapLng),
                title: item.location.addressTitle,
                map: googleMap
            });
            googleMapMarkers.push(marker);
        }
    }

});

1 个答案:

答案 0 :(得分:1)

您正在尝试将单个标记视为标记数组。

const googleMapMarkers = new google.maps.Marker( markerData ); 

这不会奏效。

为什么不在遍历项目时创建google.maps.Marker的实例,并将它们保存到数组中。您还可以在该迭代中设置每个地图。

var googleMapMarkers = [];

    for ( i; i--; ) {
                item = items[ i ];
                markerData.push({
                    position: new google.maps.LatLng(item.location.mapLat, item.location.mapLng),
                    title: item.location.addressTitle
                });

               markerData.setMap(googleMap);
               googleMapMarkers.push(markerData);
            }

这是假设markerData是一个有效的谷歌地图标记。如果不是您可能需要更多代码来构建该对象,但它很容易完成并且API参考中有大量示例。

相关问题