简体   繁体   English

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

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

Having trouble with the Google Maps API in terms of structuring the data coming off of an AJAX request. 在构造来自AJAX请求的数据方面,Google Maps API遇到了麻烦。 Here's where I'm at currently: 这是我目前所在的位置:

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

From what I understand, Google Maps wants the data in JSON and not in an array. 据我了解,Google Maps希望使用JSON而不是数组形式的数据。 What I can tweak to get to get it there? 我要如何调整才能达到目标?

New revised, working code: 新修订的工作代码:

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

});

You are trying to treat a single marker as an array of markers. 您正在尝试将单个标记视为标记数组。

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

This won't work. 这行不通。

Why not create an instance of google.maps.Marker as you are iterating through the items and save push them into an array. 为什么不遍历项目创建一个google.maps.Marker实例并将其保存到数组中。 You can also set the map of each in that iteration. 您还可以在该迭代中设置每个地图。

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

This is assuming markerData is a valid google map marker. 这是假设markerData是有效的Google Map标记。 If it isn't you may have a little more code to construct that object, but it's easily done and plenty examples in the API reference. 如果不是,您可能需要更多的代码来构造该对象,但是它很容易实现,并且在API参考中提供了很多示例。

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

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