Landitus
Landitus

Reputation: 1900

How to loop through a JSON object to fit inside a javascript array?

I'm trying to convert a JSON object with google maps markers (which are generated with data from a CMS) in a way that fits inside the GoMap declaration. I'm trying to get multiple markers from my CMS to place them on a map.

I'll try to explain it in detail below:

I loop through the markers and create an array which is encoded to json:

echo "<script>var googlePlaces = " . json_encode($googlePlaces) . ";</script>"; 

Then I get the following object:

[Object { title="Est. Avenida de Mayo",  lat="-34.60844234174374",  lon="-58.37414860725403"}, Object { title="Café Tortoni",  lat="-34.60871608361115",  lon="-58.378823697566986"}]

All I need is to fit it here:

$(document).ready(function() {

    $("#map").goMap({ 
        latitude: config.location_lat, 
        longitude: config.location_lon, 
        zoom: 15,
        mapTypeControl: false, 
        maptype: 'ROADMAP',
        navigationControl: true, 
        navigationControlOptions: { 
            position: 'TOP_LEFT', 
            style: 'SMALL' 
        },
       markers: [{  
                    // Multiple markers here!
            latitude: XXXXXX, 
            longitude: XXXXXXX, 
            html: { 
                content: 'XXXXXXX'
            },
        }]
    });     
} 
}); // end

I'm kind of stuck here, do I know I would need to loop through the JSON object somehow and place it inside the markers property in the GoMap script. Is this correct? Can anybody point me in the right direction?

Upvotes: 0

Views: 310

Answers (1)

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14302

Try Some thing like this to iterate your JSON object element and push it to in an array.

 var markersArray = new Array();

 $.each(googlePlaces, function(i, itemPlace) {
     var obj = { 
                 latitude: itemPlace.lat, 
                 longitude: itemPlace.lon,
                 html: { content: itemPlace.title }
               };        

     markesArray.push(obj);

 });​

After that in the gomap code use markersArray like this

$("#map").goMap({ 
   // your existing stuff
   markers: markersArray 
});     

Good Luck !!

Upvotes: 1

Related Questions