繁体   English   中英

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

[英]How do I properly format this JavaScript Array/Object for Google Maps?

在构造来自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 Maps希望使用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);
        }
    }

});

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

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是有效的Google Map标记。 如果不是,您可能需要更多的代码来构造该对象,但是它很容易实现,并且在API参考中提供了很多示例。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM