Google Elevation API with AJAX?
I am trying to use the Google Elevation API with the getJSON function of JQuery.
I am using this code which i开发者_运维问答s using JSONP :
jQuery.getJSON("http://maps.googleapis.com/maps/api/elevation/json?locations=23.444,45.4545&sensor=false&jsoncallback=?", function(json){
alert("a");
});
I can see in Firebug that the GET request is correctly send and I receive the correct response from Google :
{
"status": "OK",
"results": [ {
"location": {
"lat": 23.4440000,
"lng": 45.4545000
},
"elevation": 816.7996216
} ]
}
However I never the Alert and I get this error from Firebug :
invalid label
"status": "OK",\n
I am using the Google Maps API v2 so I connato use the build in method.
Is there any way to get the elevation with the Google Elevation API via an AJAX request and without creating a proxy?
Thanks for your help.
Benjamin
That API doesn't support JSONP, it's returning JSON only...so yes you'll need to proxy in this case.
To be clear, the correct response would be like this:
someFunction({
"status": "OK",
"results": [ {
"location": {
"lat": 23.4440000,
"lng": 45.4545000
},
"elevation": 816.7996216
} ]
})
jQuery replaces callback=?
with callback=someFunction
, but google doesn't use this parameter since this service doesn't support JSONP...so the problem is you're effectively doing this:
<script type="text/javascript">
{
"status": "OK",
"results": [ {
"location": {
"lat": 23.4440000,
"lng": 45.4545000
},
"elevation": 816.7996216
} ]
}
</script>
Which results in an error, as that's not valid JavaScript...you get an invalid label error. If it had the function wrapper there, it would be valid and it'd execute that function jQuery made (from your success
callback).
You should use the G̶e̶o̶L̶o̶c̶a̶t̶i̶o̶n̶ ElevationService class from the JavaScript API. There's no need to proxy.
http://code.google.com/apis/maps/documentation/javascript/reference.html#ElevationService
The Google elevation API don't support JSONP (Thanks to Nick Craver for the explanation) and I cannot use the ElevationService which is only available for the v3 Google Maps API.
So I decided to use an other webservice to get the elevation :
http://www.geonames.org/export/web-services.html#astergdem
example : http://ws.geonames.org/astergdemJSON?lat=X&lng=Y&callback=?
This webservice support JSONP, so it can be use easily with JQuery and the getJSON method.
Benjamin
As @Chris Broadfoot said, there's a special class for that in API v3 A better example here https://developers.google.com/maps/documentation/javascript/elevation You don't need to deal with JSONP nor another service.
精彩评论