谷歌地图 API;“CORS 标头‘Access

编程入门 行业动态 更新时间:2024-10-28 20:27:34
本文介绍了谷歌地图 API;“CORS 标头‘Access-Control-Allow-Origin’缺失"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 Google Maps API 计算两个地方之间的预计旅行时间.我通过以下方式要求数据:

I'm trying to calculate the estimated travel time between two places, with the Google Maps API. I am asking for the data in the following way:

const Url = 'maps.googleapis/maps/api/distancematrix/json?origins=25.7694708,-80.259947&destinations=25.768915,-80.254659&key=' + API_KEY; try { const response = await fetch(Url); console.log(response); const data = await response.json(); console.log(data.rows); } catch(e){ console.log(e); }

问题是在浏览器控制台中出现错误:

The problem is that in the browser console I get the error:

TypeError: NetworkError when attempting to fetch resource

它还向我显示了一个警告:

and it also shows me a warning:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at maps.googleapis/maps/api/distancematrix/json?origins=25.7694708,-80.259947&destinations=25.768915,-80.254659&key=API_KEY. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

但是当我查看网络部分的控制台时,它显示调用已成功完成,并显示以下 json:

But when I look at the console in the network part it shows me that the call was completed successfully and it shows me the following json:

{ "destination_addresses" : [ "3670 SW 3rd St, Miami, FL 33135, USA" ], "origin_addresses" : [ "3911 SW 2nd Terrace, Coral Gables, FL 33134, USA" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "0.9 km", "value" : 881 }, "duration" : { "text" : "2 mins", "value" : 144 }, "status" : "OK" } ] } ], "status" : "OK" }

有人可以帮我解决这个问题吗?我在网站上尝试过类似的问题,但我无法解决问题.提前致谢.

Can someone help me solve this problem? I have tried similar questions on the site but I have not been able to solve the problem. Thanks in advance.

推荐答案

您正在客户端使用距离矩阵服务.但是客户端(浏览器)站点不支持您尝试访问 API 的方式,并且它不会可靠地工作.

You are using Distance Matrix Service on client side. But the manner you trying to access the API is not supported for client(browser)-site and it will not work reliably.

很高兴有一个适用于您的用例的库:这是客户端距离矩阵服务的指南.这是一个 vanilla-js 示例 看看.

Good that there is a library for your use-case: Here's the guide for the Distance Matrix Service on client side. And here's a vanilla-js example Check it out.

也许这个片段会对你有所帮助:

Maybe this snippet will help you:

const matrix = new google.maps.DistanceMatrixService(); matrix.getDistanceMatrix({ origins: [new google.maps.LatLng(25.7694708, -80.259947)], destinations: [new google.maps.LatLng(25.768915, -80.254659)], travelMode: google.maps.TravelMode.DRIVING, }, function(response, status) { //do something });

更多推荐

谷歌地图 API;“CORS 标头‘Access

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

发布评论

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

>www.elefans.com

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