jasonbarone February 2016

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

});

Answers


KMB February 2016

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

Post Status

Asked in February 2016
Viewed 3,865 times
Voted 10
Answered 1 times

Search




Leave an answer