如何对 Google Maps API 进行跨域 AJAX 调用?

编程入门 行业动态 更新时间:2024-10-11 05:23:16
本文介绍了如何对 Google Maps API 进行跨域 AJAX 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试对 $.getJSON 调用" rel="noreferrer">Google 地图地理编码网络服务,但由于跨域安全问题,这不起作用.

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.

我无法在网上弄明白,但我已经阅读了一些关于 Google Javascript API 或 JSONP 的内容,但到目前为止还没有明确的答案......

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...

有人可以启发我吗?

谢谢!

推荐答案

我认为使用 服务器端地理编码网络服务,当 Google 地图提供全功能用于 JavaScript 的客户端地理编码 API.

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.

首先,这会自动解决您的同源问题,此外,请求限制将按客户端 IP 地址计算,而不是按服务器 IP 地址计算,这对热门站点来说可能会产生巨大的差异.

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.

这是一个使用 JavaScript Geocoding API v3 的简单示例:

Here's a very simple example using the JavaScript Geocoding API v3:

<script src="maps.google/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>

如果出于某种原因您仍然想使用服务器端网络服务,您可以设置一个非常简单的反向代理,如果您是,可以使用 mod_proxy使用阿帕奇.这将允许您为 AJAX 请求使用相对路径,而 HTTP 服务器将充当任何远程"位置的代理.

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.

在 mod_proxy 中设置反向代理的基本配置指令是 ProxyPass.您通常会按如下方式使用它:

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/ maps.google/maps/api/geocode/

在这种情况下,浏览器可以向 /geocode/output?parameters 发出请求,但服务器将通过充当 maps.google 的代理来提供服务/maps/api/geocode/output?parameters.

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 maps.google/maps/api/geocode/output?parameters.

更多推荐

如何对 Google Maps API 进行跨域 AJAX 调用?

本文发布于:2023-11-28 12:46:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642460.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Maps   Google   AJAX   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!