javascript 使用 Json 向 Google 地图添加标记 | 应用程序接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14927258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Json to add markers to Google Maps | API
提问by Michael
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.
我正在尝试使用来自 Json 响应的数据在谷歌地图上绘制标记。我一整天都在 Stack Overflow 上搜索答案,但没有找到对我有用的解决方案。
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.
我猜这与我提取 Lat & Lng 的方式有关,但我无法理解。下面是我的代码和 Json,Json 来自 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
JSON 响应
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.comas 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?
告诉使用以下代码请求 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
});
If I leave the question mark at the end I get an invalid message when I run it through http://jsonlint.comas 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?
如果我在最后留下问号,当我通过http://jsonlint.com运行它时会收到一条无效消息,因为 Json 的开头有一个问号。将其取出似乎可以解决问题,但我不是 100% 确定可以吗?
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?
当我在调试器中查看代码时,我收到“ 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
}
}
Any help would be greatly appreciated. Thanks
任何帮助将不胜感激。谢谢
Updated
更新
采纳答案by 1Mayur
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.
您使用的 API 不支持回调。您需要创建一个代理,并且必须从您的代码中点击代理,您的代理将依次调用 api。
here is the code
这是代码
index.html
索引.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
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.
然后它会出现。
回答by The Alpha
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 exampleusing valid (edited) json
which is printing lat, lng
in the console.
你json
的无效,"resultsPage:" {
应该是"resultsPage" : {
,冒号在双引号内,你可以json
使用jsonlint.com验证你的。这是在控制台中打印的使用有效(已编辑)的示例。json
lat, lng
Invalid json error from jsonlint.com
来自无效的 json 错误 jsonlint.com
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>
回答by Om Shankar
The &jsoncallback=?
can be deleted safely
该&jsoncallback=?
可以安全地删除
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).
然后,您不需要(可能)json 回调,因为您已经在逗号后面使用了一个回调(getJSON
函数的第二个参数)。
So you can simply deletethe &jsoncallback=?
from your URL and make it to http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}
所以,你可以简单地删除该&jsoncallback=?
从你的网址,并使其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
-- 为了方便 JSONP(和跨域 AJAX 请求),您正在向callback
URL发送一个函数
-- The Server then reads the jsoncallback=XYZ
and then returns you the data wrapped inXYZ
function call
-- 服务器然后读取jsoncallback=XYZ
并返回封装在XYZ
函数调用中的数据
-- So that you can define XYZ
function in your JavaScript somewhere
like the following:
-- 这样你就可以XYZ
在你的 JavaScript 中定义函数,如下所示:
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
-- 但是由于您已经有一个函数的回调getJSON
函数,您不需要&jsoncallback=something
,因此可以删除它
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:
PS:作为上述证明,请尝试http://api.songkick.com/api/3.0/events.json?location=clientip&apikey={your_api_key}&jsoncallback=MyFunction
在浏览器中点击 URL ,您将在一行中得到以下响应:
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
更新:
为了解决您在评论中的 JavaScript 错误——
即使响应是有效的JSON
,您也将响应用作JavaScript
代码,这是无效的
It would be a valid JavaScript
code if you make it like this:
JavaScript
如果你这样做,这将是一个有效的代码:
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
但我的观点是,你为什么要用这个 JSON 数据检查控制台错误?控制台用于JavaScript