如何获取 API 的 JSON 结果并在地图上绘制

我有一个工作示例,说明如何控制台从外部 API 返回的日志 JSON 数据。我还有一个如何将地理编码数据绘制为 Google 地图上的标记的工作示例。我尝试将它们组合在下面的代码示例中(非常糟糕)。

我不能做的是让两者一起工作,即调用 API 并传递要在地图上绘制的地理编码数据。以下是我的代码示例,用于调用 API、加载 Google 地图并控制台记录地理编码数据(我已删除 Google 密钥[因此请插入您自己的密钥进行测试],但保留了 RapidAPI 密钥):

<!DOCTYPE html>

<html dir="ltr">


<head>

  <meta charset="utf-8">

  <meta name="viewport" content="width=\, initial-scale=1.0">

  <meta http-equiv="X-UA-Compatible" content="ie=edge"  />

  <title>Javascript Calling APIs</title>

  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

  <script src="https://maps.googleapis.com/maps/api/js?key=ENTER_GOOGLE_KEY_HERE&callback=initMap&libraries=&v=weekly" defer></script>

  <style type="text/css">

    /* Always set the map height explicitly to define the size of the div

       * element that contains the map. */

    #map {

      height: 100%;

    }


    /* Optional: Makes the sample page fill the window. */

    html,

    body {

      height: 100%;

      margin: 0;

      padding: 0;

    }

  </style>

</head>


<body>

  <h1>Test</h1>

  <div id="map"></div>

  <p id="demo"></p>


  <input type="text" placeholder="Type something..." id="myInput">

  <button type="button" onclick="getInputValue();">Get Value</button>



  <script>

  function getInputValue() {

  var myHeaders = new Headers();

  myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");


  var town = document.getElementById("myInput").value;


  var requestOptions = {

    method: 'GET',

    headers: myHeaders,

    redirect: 'follow'

  };

}


var myHeaders = new Headers();

myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");

  const api_url = 'https://wyre-data.p.rapidapi.com/restaurants/town'

  var town = document.getElementById("myInput").value;

  var requestOptions = {

    method: 'GET',

    headers: myHeaders,

    redirect: 'follow'

  };

牛魔王的故事
浏览 87回答 1
1回答

缥缈止盈

要根据 API 的响应在地图上放置标记,请将此代码添加到响应的处理中:let pot = { // existing code&nbsp; lat: la,&nbsp; lng: lo};let marker = new google.maps.Marker({&nbsp; position: pot,&nbsp; map: map})&nbsp;但是,您还需要重新排列代码以在函数getInputValue运行时发出请求(目前它在创建地图之前运行,并且字段的初始值<input>(在发布的代码中为空))。像这样的东西:function getInputValue() {&nbsp; var myHeaders = new Headers();&nbsp; myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");&nbsp; var town = document.getElementById("myInput").value;&nbsp; var requestOptions = {&nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; headers: myHeaders,&nbsp; &nbsp; redirect: 'follow'&nbsp; };&nbsp; var myHeaders = new Headers();&nbsp; myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");&nbsp; const api_url = 'https://wyre-data.p.rapidapi.com/restaurants/town'&nbsp; var town = document.getElementById("myInput").value;&nbsp; var requestOptions = {&nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; headers: myHeaders,&nbsp; &nbsp; redirect: 'follow'&nbsp; };&nbsp; function getTown() {&nbsp; &nbsp; const response = await fetch(api_url + '/' + town, requestOptions);&nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; console.log(data);&nbsp; &nbsp; let la = data[0].Geocode_Latitude;&nbsp; &nbsp; let lo = data[0].Geocode_Longitude;&nbsp; &nbsp; let pot = {&nbsp; &nbsp; &nbsp; lat: la,&nbsp; &nbsp; &nbsp; lng: lo&nbsp; &nbsp; };&nbsp; &nbsp; let marker = new google.maps.Marker({&nbsp; &nbsp; &nbsp; position: pot,&nbsp; &nbsp; &nbsp; map: map&nbsp; &nbsp; })&nbsp; &nbsp; console.log(pot);&nbsp; }&nbsp; getTown();}概念证明小提琴代码片段:function getInputValue() {&nbsp; var myHeaders = new Headers();&nbsp; myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");&nbsp; var town = document.getElementById("myInput").value;&nbsp; var requestOptions = {&nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; headers: myHeaders,&nbsp; &nbsp; redirect: 'follow'&nbsp; };&nbsp; var myHeaders = new Headers();&nbsp; myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");&nbsp; const api_url = 'https://wyre-data.p.rapidapi.com/restaurants/town'&nbsp; var town = document.getElementById("myInput").value;&nbsp; var requestOptions = {&nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; headers: myHeaders,&nbsp; &nbsp; redirect: 'follow'&nbsp; };&nbsp; function getTown() {&nbsp; &nbsp; // use provided response instead of response from server&nbsp; &nbsp; //&nbsp; const response = await fetch(api_url + '/' + town, requestOptions);&nbsp; &nbsp; //&nbsp; const data = await response.json();&nbsp; &nbsp; const data = [{&nbsp; &nbsp; &nbsp; AddressLine2: "Hallgate Lane",&nbsp; &nbsp; &nbsp; AddressLine3: "Stalmine",&nbsp; &nbsp; &nbsp; BusinessName: "MCCOLLS",&nbsp; &nbsp; &nbsp; Geocode_Latitude: 53.901518,&nbsp; &nbsp; &nbsp; Geocode_Longitude: -2.953877,&nbsp; &nbsp; &nbsp; PostCode: "FY6 0LA",&nbsp; &nbsp; &nbsp; RatingValue: 5,&nbsp; &nbsp; &nbsp; _id: "5fc96b3a9c728ca91c564485",&nbsp; &nbsp; }];&nbsp; &nbsp; console.log(data);&nbsp; &nbsp; let la = data[0].Geocode_Latitude;&nbsp; &nbsp; let lo = data[0].Geocode_Longitude;&nbsp; &nbsp; let pot = {&nbsp; &nbsp; &nbsp; lat: la,&nbsp; &nbsp; &nbsp; lng: lo&nbsp; &nbsp; };&nbsp; &nbsp; let marker = new google.maps.Marker({&nbsp; &nbsp; &nbsp; position: pot,&nbsp; &nbsp; &nbsp; map: map&nbsp; &nbsp; })&nbsp; &nbsp; console.log(pot);&nbsp; }&nbsp; getTown();}let map;function initMap() {&nbsp; map = new google.maps.Map(document.getElementById("map"), {&nbsp; &nbsp; center: {&nbsp; &nbsp; &nbsp; lat: 53.4808,&nbsp; &nbsp; &nbsp; lng: -2.2426&nbsp; &nbsp; },&nbsp; &nbsp; zoom: 7,&nbsp; });&nbsp; addMarker(pot);&nbsp; //add marker function&nbsp; function addMarker(coords) {&nbsp; &nbsp; var marker = new google.maps.Marker({&nbsp; &nbsp; &nbsp; position: coords,&nbsp; &nbsp; &nbsp; map: map,&nbsp; &nbsp; &nbsp; icon: 'pin.png'&nbsp; &nbsp; });&nbsp; }}/* Always set the map height explicitly to define the size of the div&nbsp; &nbsp; &nbsp; &nbsp;* element that contains the map. */#map {&nbsp; height: 60%;}/* Optional: Makes the sample page fill the window. */html,body {&nbsp; height: 100%;&nbsp; margin: 0;&nbsp; padding: 0;}<!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <title>Simple Markers</title>&nbsp; &nbsp; <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>&nbsp; &nbsp; <script&nbsp; &nbsp; &nbsp; src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly"&nbsp; &nbsp; &nbsp; defer&nbsp; &nbsp; ></script>&nbsp; &nbsp; <!-- jsFiddle will insert css and js -->&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; &nbsp; <h1>Test</h1>&nbsp; <div id="map"></div>&nbsp; <p id="demo"></p>&nbsp; <input type="text" placeholder="Type something..." id="myInput">&nbsp; <button type="button" onclick="getInputValue();">Get Value</button>&nbsp; </body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript