簡體   English   中英

使用Json將標記添加到Google Maps | API

[英]Using Json to add markers to Google Maps | API

我正在嘗試使用來自Json Response的數據在Google地圖上繪制標記。 我已經搜索了Stack Overflow一整天的答案,但是沒有設法找到一個對我有用的解決方案。

我猜這與我提取Lat&Lng的方式有關,但是我不能把手指放在它上面。 下面是我的代碼和Json,Json來自API。

我的代碼中的錯誤在哪里?

腳本

<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回復

通過使用以下代碼告知請求Json數據。 如果我在最后留下問號,當我通過http://jsonlint.com運行它時會得到一條無效的消息,因為在Json的開頭有一個問號。 拿出來似乎解決了這個問題,但我不是百分之百確定這是好的嗎?

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

如果我在最后留下問號,當我通過http://jsonlint.com運行它時會得到一條無效的消息,因為在Json的開頭有一個問號。 拿出來似乎解決了這個問題,但我不是百分之百確定這是好的嗎?

當我在調試器中查看代碼時,我得到“SyntaxError:Unexpected token':'”,但是這個響應來自API,所以我不確定我能做些什么呢?

    {
    "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
    }
    }  

任何幫助將不勝感激。 謝謝

更新

能夠重現你的錯誤。

您正在使用的API不支持回調。 你需要創建一個代理,並且必須從你的代碼中命中代理,你的代理將依次調用api。

這是代碼

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

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 . ');';
?>

然后它會出現。

您的json無效, "resultsPage:" {應該是"resultsPage" : { ,冒號在雙引號內,您可以使用jsonlint.com驗證您的json 這是一個使用有效(已編輯) json示例 ,它在控制台中打印lat, lng

來自jsonlint.com json錯誤無效

在此輸入圖像描述

更新:你也可以嘗試這個(用於檢查)

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>

&jsoncallback=? 可以安全刪除

以下是我對此的看法:

如果您使用以下代碼:

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

然后,你不需要(可能)一個json回調,因為你已經在逗號之后使用了一個(第二個參數是getJSON函數)。

所以你可以簡單地刪除 &jsoncallback=? 從您的網址轉到http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}

這是發生了什么 -

- 為了方便JSONP(和跨域AJAX請求),您要向URL發送callback函數

- 然后,服務器讀取jsoncallback=XYZ ,然后返回包含在 XYZ函數調用中的數據

- 這樣你就可以在JavaScript中定義XYZ函數,如下所示:

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

- 但是因為你已經有一個函數回調getJSON函數,你不需要&jsoncallback=something ,因此可以刪除它

PS :作為上述證據,請嘗試在瀏覽器中點擊URL http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}&jsoncallback=MyFunction ,您將得到以下回復在一行:

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

更新:
在評論中解決您的JavaScript錯誤 -
即使響應是有效的JSON ,您也將響應用作JavaScript代碼,這是無效的

如果您這樣做,它將是一個有效的JavaScript代碼:

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

但我的觀點是,為什么用這個JSON數據檢查控制台錯誤? 控制台適用於JavaScript

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM