带有Google地理编码API的json [英] json with google geocoding api
问题描述
这是进入位置后能获得纬度和经度的代码.我相信我的代码是我所知,但是进入一个位置后我得到了空白页.
Here is code which gets latitude and longitute when entered a location.I believe that my code right according to my knowledge.but i get a blank page after entering a place.
这是代码:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url="http://maps.googleapis.com/maps/api/geocode/json?address=";
var query;
var sensor="&sensor=false";
var callback="&callback=?";
$("button").click(function(){
query=$("#query").val();
$.getJSON(url+query+sensor+callback,function(json){
$('#results').append('<p>Latitude : ' + json.results.geometry.location.lat+ '</p>');
$('#results').append('<p>Longitude: ' + json.results.geometry.location.lng+ '</p>');
});
});
});
</script>
</head>
<body>
<input type="text" id="query" /><button>Get Coordinates</button>
<div id="results"></div>
</body>
</html>
推荐答案
您正在此处尝试使用JSONP.
You're trying to use JSONP here.
JSONP
如果URL包含字符串"callback =?" (或类似,由服务器端API定义),则将request>视为JSONP.有关更多详细信息,请参见$ .ajax()中有关jsonp数据类型的讨论.
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request > is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
重要提示:从jQuery 1.4开始,如果JSON文件包含语法错误,则请求通常会静默失败.
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.
请参阅: http://api.jquery.com/jQuery.getJSON/
但是您所调用的URL返回普通 JSON,因此解析失败并出现语法错误,getJSON
静默失败.
But the URL you're calling returns plain JSON, so the parsing fails with a syntax error and getJSON
fails silently.
现在,当您尝试更改地理编码网址以使用JSONP时,会出现404
错误,因为Google早已删除了对JSONP的支持:
Now when you try to change the geocode URL to use JSONP, you get a 404
error since Google has removed support for JSONP quite a while ago:
- http://code.google.com/p/gmaps-api -issues/issues/detail?id = 1872
- http://blog.mikecouturier.com/2009 /11/jsonp-and-google-maps-api-geocoder-not.html
- http://code.google.com/p/gmaps-api-issues/issues/detail?id=1872
- http://blog.mikecouturier.com/2009/11/jsonp-and-google-maps-api-geocoder-not.html
简而言之:
您不能再简单地使用浏览器JavaScript中的地理编码api,而必须在服务器上添加代理脚本.
In short:
You cannot simply use the geocode api from Browser JavaScript anymore, you'll have to add a proxy script on your server.
即使请求可以正常工作,您的代码中仍然存在错误:
And even if the request would work, your code still has a bug in it:
json.results
是结果的数组,因此它没有geometry
属性.
json.results
is an array of results, so it has no geometry
property.
您必须访问数组的第一个元素才能访问具有geometry
属性的实际对象:
You have to access the first element of the array in order to get to the actual object that has the geometry
property:
json.results[9].geometry.location.lng
这篇关于带有Google地理编码API的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!