【问题标题】:Using Json to add markers to Google Maps | API使用Json 向谷歌地图添加标记| API
【发布时间】:2013-02-02 08:23:44
【问题描述】:

我正在尝试使用来自 Json 响应的数据在谷歌地图上绘制标记。我整天都在 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 的开头有一个问号。把它拿出来似乎可以解决问题,但我不是 100% 确定这样可以吗?

    $.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 的开头有一个问号。把它拿出来似乎可以解决问题,但我不是 100% 确定这样可以吗?

当我在调试器中查看代码时,我收到“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
    }
    }  

任何帮助将不胜感激。谢谢

更新

【问题讨论】:

  • 你使用json变量作为参数,循环使用data$.each(data["resultsPage"]["results"]["event"]首先应该是$.each(json["resultsPage"]["results"]["event"]
  • 谢谢...我想我已经盯着这个屏幕太久了!
  • 问题是什么? “它不起作用”是不够的信息。您是否收到任何错误消息?您是否使用调试器单步调试过您的代码?
  • @gilly3 也许不是最清楚的问题,但我写的时候很累!我完全不知所措,我花了几个小时进行小改动,看看它们是否有效果,但什么也没有……我没有收到任何错误,但我没有从我的 Json 响应中得到错误,“出乎意料':'"...但是这个响应来自一个 API,所以不太确定我能做些什么?
  • 把代码发邮件给我sirwanimayur@gmail.com

标签: javascript json google-maps google-maps-api-3 getjson


【解决方案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 . ');';
?>

然后它就会出现。

【讨论】:

  • 这太棒了@SirwaniMayur
【解决方案2】:

您的json 无效,"resultsPage:" { 应为"resultsPage" : {,冒号在双引号内,您可以使用jsonlint.com 验证您的json。这是一个使用有效(已编辑)jsonexample,它在控制台中打印 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>

【讨论】:

  • 我之前发布的回复取自文档,您知道这是错误的!!!很抱歉浪费您的时间。我已经用真实的响应更新了我的答案,我已经通过 jsonlint.com 运行它并且它返回有效。
  • @Michael,请检查更新后的答案,看看你得到了什么,实际上我仍然不确定你在说什么问号。
  • 在 API 请求结束时 "&jsoncallback=?"... 这一直让我感到困惑,我收到一个错误,但我有点认为它是必需的,或者他们为什么会这样做包括它!
【解决方案3】:

&amp;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 函数的第二个参数)。

所以您可以简单地删除您的 URL 中的 &amp;jsoncallback=? 并将其设置为 http://api.songkick.com/api/3.0/events.json?location=clientip&amp;apikey={your_api_key}

这是怎么回事 -

-- 为了方便 JSONP(和跨域 AJAX 请求),您正在向 URL 发送 callback 函数

-- 服务器然后读取jsoncallback=XYZ,然后返回数据包装在 XYZ 函数调用

-- 这样你就可以在 JavaScript 中的某个地方定义 XYZ 函数 像下面这样:

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

-- 但是由于您已经对getJSON 函数进行了有效回调,因此您不需要&amp;jsoncallback=something,因此可以将其删除

PS:作为上述证明,尝试在浏览器中点击 URL http://api.songkick.com/api/3.0/events.json?location=clientip&amp;apikey={your_api_key}&amp;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

【讨论】:

  • 感谢您的回复,尤其是您试图向我解释到底发生了什么,而不仅仅是告诉它可以放弃它......我已经通过 JSONLINT 运行它,它很好.. . 但是我的控制台说有一个意外的':',你觉得没关系吗?
  • @Michael, console 给出错误,因为您将 JSON 响应作为 JavaScript 代码执行。它是一个有效的 JSON 但不是有效的JavaScript。如果您将var abc = 放在控制台中的 JSON 之前,错误就消失了!
  • @Michael,另外,您已经接受了一个替代解决方案的答案。答案说 API 不支持回调,这是错误的。我给了你一个发送any_string_as_a_callback 到songkick 的例子,JSON 包含在回调中。所以它确实支持!!
猜你喜欢
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
相关资源
最近更新 更多