当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Can I call the google maps directions API from a web page (as opposed to a server)?

问题描述:

I am a long time programmer (C, Python, FORTRAN), but this is my first foray into javascript and anything web, so I am learning on the fly.

So, the main question up front: Can I use the google maps directions API from a script section of a simple web page on my laptop, or does it need to be called from a server?

I have an API key and I have successfully used parts of the API that are called as functions (Map, Geometry). I am trying to use the google maps directions API, which as I understand it, you must use via a URL and an HTTP GET. Here is a sample URL that my code has constructed:

https://maps.googleapis.com/maps/api/directions/json?origin=45.0491174%2C-93.46037330000001&destination=45.48282401917292%2C-93.46037330000001&key="my key"

If I paste that URL into the address bar, it works. I get a document back with the directions info. If I execute it from inside a script section on a simple web page I am building, the response I get is:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I did some searching, both in stackoverflow and elsewhere on the web and I came across this:

http://www.html5rocks.com/en/tutorials/cors/

Per that page, I checked to make sure that withCredentials was supported and then I set withCredentials to true. This did not alter the outcome. Obviously, the API works, so I am now wondering if I have to do this from a web server and not from a simple web page to get around the cross-domain limitations. I am hoping to avoid having to set up a server since this is a one-off for my own personal use, but maybe I dont have a choice?

As an aside, does anyone have any insight into why the directions API is called via a URL rather than as a javascript function like many of the others?

网友答案:

To answer the main question, Yes. You can definitely use the GoogleMap Directions API inside your web page. To get you started quick and easy, follow this link . Then,

  1. Click on the JAVASCRIPT + HTML version, copy the whole code and paste it into a text editor and save it as an html file.

  2. Start your own local server (like node.js). Dont forget to obtain a Browser API key and set your HTTP refferer (example http://localhost:4567) in Google Developer Console or you will get errors.

  3. Run your html file on your local server (example http://localhost:4567/myprojfolder/samplewebfile.html) .

You can do this with all Google Maps JavaScript API samples. If you're curious about setting a node.js server, there are plenty of resources online.

分享给朋友:
您可能感兴趣的文章:
随机阅读: