繁体   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