I'm trying to make a jQuery $.getJSON
call to the Google Maps Geocoding webservice, but this doesn't work because of cross-domain security issues.
I haven't been able to figure it out online, but I've read a bit about Google Javascript API or JSONP, but so far no clear answer...
Could anyone enlight me?
Thanks!
For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.
Designed to compete with well-established mapping sites, Google Maps uses Ajax to avoid reloading its main page at all (see Figure 1-4). Unlike other mapping web applications, Google Maps enables you to drag the map to move it in various directions.
CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.
I can see no advantage in using the Server-side Geocoding Web Service when Google Maps provides a full featured Client-side Geocoding API for JavaScript.
First of all, this automatically solves your same-origin problem, and in addition the request limits would be calculated per client IP address instead of of per server IP address, which can make a huge difference for a popular site.
Here's a very simple example using the JavaScript Geocoding API v3:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> var geocoder = new google.maps.Geocoder(); var address = 'London, UK'; if (geocoder) { geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log(results[0].geometry.location); } else { console.log("Geocoding failed: " + status); } }); } </script>
If for some reason you still want to use the server-side web-service, you could set up a very simple reverse proxy, maybe using mod_proxy if you are using Apache. This would allow you to use relative paths for your AJAX requests, while the HTTP server would be acting as a proxy to any "remote" location.
The fundamental configuration directive to set up a reverse proxy in mod_proxy is the ProxyPass. You would typically use it as follows:
ProxyPass /geocode/ http://maps.google.com/maps/api/geocode/
In this case, the browser could make a request to /geocode/output?parameters
but the server would serve this by acting as a proxy to http://maps.google.com/maps/api/geocode/output?parameters
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With