OpenStreetMap's Nominatim API now does support JSONP so you can get data purely with client side code, needing nothing extra on your own server. Here's a jsfiddle example - if you can do it in jsfiddle, you can do it anywhere.
For the more general question of how to access APIs from other domains, here's some useful things I've learned while wading through the many partially complete and often contradictory answers out there, and through trial and error. Please edit or comment if anything is or becomes inaccurate.
- If you can't use an API that supports JSONP, you need to look into plugins like jquery-xdomain-ajax using things like YQL and understand how they work. Generally, these plugins seem geared for reading HTML more than querying APIs.
- To be able to access an API directly it must a) offer results in JSON and b) have built in JSONP support which means:-
- The API must be set up to listen out for a parameter which tells it the name of the function to wrap its result in
- You must find out what that parameter is called. In OSM's case, it is called
json_callback
, jQuery's default callback
will only work if by chance that's what the API is programmed to listen for
- With jQuery, it is this API-specific parameter key which should go at the end of your query URL with
?
(e.g. if it's json_callback
, then someurl.com/api?json_callback=?
). jQuery figures out what this is, swaps the ?
for a string like jQuery1712164863864387412
, names the inline function with the same string, and waits to receive some code that triggers that function by name and passes it the JSON.
- If the request works but the callback doesn't fire and you see an error like
parseerror jQuery17109935275333671539_1300495251986 was not called
, it means jQuery has the function named, ready and waiting, but the API hasn't used that string to wrap the JSON so the function isn't called - likely meaning you're not using the right parameter name
- Without jQuery, you need to pass that parameter key the name of a named function that will receive the JSON
- Since essentially all that's happening is the browser is loading then in a controlled way running a snippet of javascript code equivalent to
someFunction({"some": "argument"});
, error handling is limited (but see the jsfiddle for what jQuery offers if you use the full $.ajax
syntax instead of the stripped down $.getJSON
shortcut)
- In Firebug for me at least JSONP requests don't appear in the console like other AJAX calls, rather, they're at the bottom of the NET panel (since, under the hood, it's essentially a round-the-back way of loading code, handled more like say
<script>
).
Hopefully this will help someone!