6

I'm trying to plot markers on a google map using data from a Json Response. I have searched Stack Overflow for an answer all day but havn't managed to find a solution that has worked for me.

I'm guessing it has something to do with the way I am extracting the Lat & Lng but just can't put my finger on it. Below are my code and the Json, the Json is from an API.

Where is the error in my code?

Script

<script>   
  function initialize() {
              var myOptions = {
                  zoom: 4,
                  center: new google.maps.LatLng(34.397, 150.644),
                  mapTypeId: google.maps.MapTypeId.ROADMAP
              };

              map = new google.maps.Map(document.getElementById("map"), myOptions);
              };

  function getLocations() {

      $.getJSON("URL", function (json) {

          $.each(json["resultsPage"]["results"]["event"], function(i, entry){
              addMarker(entry.location.lat,entry.location.lng);
          });
      });
  }

  function addMarker(lat,lng) {
          marker = new google.maps.Marker({
          position: new google.maps.LatLng(lat,lng),
          map: map,
          });
          markersArray.push(marker);
  }
  </script>

Json Response

Told to request Json data by using the following code. If I leave the question mark at the end I get an invalid message when I run it through http://jsonlint.com as there is a question mark at the beginning of the Json. Taking that out appears to solve the problem but I'm not 100% sure that that is ok?

    $.getJSON("http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}&jsoncallback=?",
    function(data){
    // data is JSON response object
    });

If I leave the question mark at the end I get an invalid message when I run it through http://jsonlint.com as there is a question mark at the beginning of the Json. Taking that out appears to solve the problem but I'm not 100% sure that that is ok?

When I view the code in debugger I get " SyntaxError: Unexpected token ':' ", but this response is coming from an API so I am unsure what I can do about it?

    {
    "resultsPage": {
    "status": "ok",
    "results": {
        "event": [
            {
                "type": "Concert",
                "status": "ok",
                "performance": [
                    {
                        "artist": {
                            "displayName": "Arcade Fire",
                            "uri": "http://www.songkick.com/artists/66758-arcade-fire?utm_source=16289&utm_medium=partner",
                            "identifier": [
                                {
                                    "mbid": "52074ba6-e495-4ef3-9bb4-0703888a9f68",
                                    "href": "http://api.songkick.com/api/3.0/artists/mbid:52074ba6-e495-4ef3-9bb4-0703888a9f68.json"
                                }
                            ],
                            "id": 66758
                        },
                        "billingIndex": 1,
                        "billing": "headline",
                        "displayName": "Arcade Fire",
                        "id": 29913729
                    },
                    {
                        "artist": {
                            "displayName": "Doody and Kami",
                            "uri": "http://www.songkick.com/artists/6334389-doody-and-kami?utm_source=16289&utm_medium=partner",
                            "identifier": [],
                            "id": 6334389
                        },
                        "billingIndex": 2,
                        "billing": "support",
                        "displayName": "Doody and Kami",
                        "id": 29913734
                    },
                    {
                        "artist": {
                            "displayName": "Leah Gordon",
                            "uri": "http://www.songkick.com/artists/6334394-leah-gordon?utm_source=16289&utm_medium=partner",
                            "identifier": [],
                            "id": 6334394
                        },
                        "billingIndex": 3,
                        "billing": "support",
                        "displayName": "Leah Gordon",
                        "id": 29913739
                    }
                ],
                "venue": {
                    "metroArea": {
                        "country": {
                            "displayName": "Canada"
                        },
                        "state": {
                            "displayName": "QC"
                        },
                        "displayName": "Montreal",
                        "uri": "http://www.songkick.com/metro_areas/27377-canada-montreal?utm_source=16289&utm_medium=partner",
                        "id": 27377
                    },
                    "lat": 45.5014288,
                    "displayName": "Phi Center",
                    "lng": -73.5564459,
                    "uri": "http://www.songkick.com/venues/1973969-phi-center?utm_source=16289&utm_medium=partner",
                    "id": 1973969
                },
                "popularity": 0,
                "location": {
                    "lat": 45.5014288,
                    "lng": -73.5564459,
                    "city": "Montreal, QC, Canada"
                },
                "start": {
                    "time": null,
                    "date": "2013-02-23",
                    "datetime": null
                },
                "displayName": "Arcade Fire with Doody and Kami and Leah Gordon at Phi Center (February 23, 2013)",
                "uri": "http://www.songkick.com/concerts/15215934-arcade-fire-at-phi-center?utm_source=16289&utm_medium=partner",
                "id": 15215934
            }
        ]
    },
    "perPage": 50,
    "page": 1,
    "totalEntries": 1
    }
    }  

Any help would be greatly appreciated. Thanks

Updated

9
  • 2
    You are using json variable as parameter and looping using data, $.each(data["resultsPage"]["results"]["event"] should be $.each(json["resultsPage"]["results"]["event"] at first. Commented Feb 17, 2013 at 23:17
  • Thanks... I think I've been staring at this screen for too long! Commented Feb 17, 2013 at 23:20
  • What is the question? "It doesn't work" is not enough information to go off of. Are you getting any error messages? Have you stepped through your code with a debugger? Commented Feb 20, 2013 at 21:59
  • @gilly3 Perhaps not the clearest question but I was very tired when I wrote it! I'm just completely at a loss, I've spent hours making small changes to see if they have an effect and nothing... I hadn't been getting any errors but I am not getting one from my Json Response, "Unexpected ':'"... But this responce is coming from an API so not too sure what I can do about it? Commented Feb 21, 2013 at 10:09
  • mail me the code [email protected] Commented Feb 25, 2013 at 14:08

3 Answers 3

6
+50

Was able to reproduce you error.

The API which you are consuming doesn't support callback. you need to create a proxy and have to hit proxy from you code and your proxy will in turn call the api.

here is the code

index.html

        function getLocations() {
            $.ajax({
                type: "GET",
                url: "http://172.20.6.114/ontrack/data.php?callback=?",
                dataType: "jsonp",
                success: function(json){
                    $.each(json["resultsPage"]["results"]["event"], function(i, entry){
                        PlotMarker(entry.location.lat, entry.location.lng);
                    });
                },
                error: function(err){
                    console.log(err);
                }
            });
        }

        function PlotMarker(lat, lon){
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat, lon),
                map: gmap,
                draggable: false,
                animation: google.maps.Animation.DROP
            });
            markerLocations.push(marker);
        }

Code for data.php

<?
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}");

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close($ch);

echo $_GET['callback'] . '(' . $server_output . ');';
?>

Then it will show up.

Sign up to request clarification or add additional context in comments.

1 Comment

Well this was awesome @SirwaniMayur
2

Your json is invalid, "resultsPage:" { should be "resultsPage" : {, the colon is inside the double quotes, you can validate your json using jsonlint.com. Here is an example using valid (edited) json which is printing lat, lng in the console.

Invalid json error from jsonlint.com

enter image description here

Update: You can also try this (for checking)

function myCallBack(data){
    console.log(data);
}
<script type="text/javascript" src="http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}&jsoncallback=myCallBack"></script>

3 Comments

That response I posted earlier was taking from the documentation and as you know was wrong!!! Sorry for wasting your time. I've updated my answer with a real response, which I have ran through jsonlint.com and it came back as valid.
@Michael, Pleaase check the updated answer and see what you get, actually I'm still not sure what question mark your talking about.
at the end of the API request "&jsoncallback=?"... It's this that has been confusing me, with it I get an error but I kind of assumed it was needed or why else would they include it!
0

The &jsoncallback=? can be deleted safely

Here's my view on that:

If you use the following code:

$.getJSON("http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}&jsoncallback=?",
    function(data){
    // data is JSON response object
    });

Then, you don't need (probably) a json callback, since you are already using one after the comma (2nd parameter to getJSON function).

So you can simply delete the &jsoncallback=? from your URL and make it to http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}

Here's what is going on -

-- To facilitate JSONP (and Cross Domain AJAX request) you are sending a callback function to the URL

-- The Server then reads the jsoncallback=XYZ and then returns you the data wrapped in XYZ function call

-- So that you can define XYZ function in your JavaScript somewhere like the following:

function XYZ(jsonDATA) {
    // ... And do things Here. JSONP is cool !    
}

-- But Since you already have a functioning callback to the getJSON function, you don't need the &jsoncallback=something and can therefore delete it

PS: as a proof to above, try hitting the URL http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}&jsoncallback=MyFunction in your browser and you will get the following response in one line:

MyFunction({
    "resultsPage": {
        "status": "error",
        "error": {
            "message": "Invalid or missing apikey"
        }
    }
})

UPDATE:
To address your JavaScript error in comment --
Even though the response is a valid JSON, you are using the response as a JavaScript code, which is invalid

It would be a valid JavaScript code if you make it like this:

var myData = {
    "resultsPage": {
        "status": "error",
        "error": {
            "message": "Invalid or missing apikey"
        }
    }
}

But my point is, why are you checking the console error with this JSON data? Console is for JavaScript

3 Comments

Thankyou for your response, especially for trying to explain to me exactly what was going on and not just telling it was fine to drop it... I have ran it through JSONLINT and it is fine... But my console says there is an unexpected ':', you think it's alright tho?
@Michael, console is giving error because you are executing the JSON response as a JavaScript code. Its a valid JSON but not valid JavaScript. If you put var abc = before your JSON in console, the error is gone !!
@Michael, also, you have accepted an answer which is an alternate solution. The answer says the API does not support callback, which is wrong. I gave you an example of sending any_string_as_a_callback to songkick, and the JSON comes wrapped in the callback. So it does support !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.