Michael
Michael

Reputation: 621

Using Json to add markers to Google Maps | API

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

Upvotes: 6

Views: 11718

Answers (3)

Om Shankar
Om Shankar

Reputation: 8069

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

Upvotes: 0

1Mayur
1Mayur

Reputation: 3485

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.

Upvotes: 6

The Alpha
The Alpha

Reputation: 146239

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>

Upvotes: 2

Related Questions