Reputation: 189
How do I access this json data using this jquery script?
The original script worked with a JSON file in which all the data was nested under "markers:" My JSON isn't nested like that. So I am having trouble figuring out how to access it correctly.
Been tinkering with this and researching other examples, but seems like others are working with a JSON file that is more similar to the original docs.
My Script:
<script type="text/javascript">
$(function() {
// Also works with: var yourStartLatLng = '59.3426606750, 18.0736160278';
$('#map_canvas').gmap().bind('init', function() {
// This URL won't work on your localhost, so you need to change it
// see http://en.wikipedia.org/wiki/Same_origin_policy
$.getJSON( 'http://localhost:3000/locations.json', function(data) {
$.each( data, function(marker) {
$('#map_canvas').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true,
}).click(function() {
$('#map_canvas').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
});
</script>
My JSON:
[
{
"id": 2,
"address": "woo woo woo",
"latitude": 10.6959353,
"longitude": -61.13116189999999,
"url": "locations/2.json"
},
{
"id": 3,
"address": "hi hi hi",
"latitude": 20.784575,
"longitude": -73.9488803,
"url": "/locations/3.json"
},
{
"id": 4,
"address": "blah blah balh",
"latitude": 50.70984199999999,
"longitude": -72.958056,
"url": "/locations/4.json"
}
]
Upvotes: 1
Views: 97
Reputation: 1467
It looks as if you have two problems in your code. First, your function in the $.each
callback should accept two parameters, the first of which is the index of the current element in the array:
$.each( data, function(idx, marker) {
Here, marker
is not an existing property or requirement in your data or data structure, but rather a placeholder name for the object at position idx
in your array. For example, when idx=0
, you will find
marker === {
"id": 2,
"address": "woo woo woo",
"latitude": 10.6959353,
"longitude": -61.13116189999999,
"url": "locations/2.json"
}
This points to the second problem, which is that the objects in your JSON file don't have a content
property, so in the click function marker.content
will be undefined.
If that's not enough to get you going, then please provide some more information about the behaviour that you're expecting to see, what's happening instead, any messages that might be appearing in your javascript console, etc.
UPDATE: In response to the comment thread, in addition to the originally missing code, the complete solution also includes not violating the same-origin policy. The JSON file being loaded must be loaded by the browser from the same location as the page containing the script.
Upvotes: 1