【问题标题】:Making GET request to Google Maps API returning bad request 400 error - javascript向 Google Maps API 发出 GET 请求返回错误请求 400 错误 - javascript
【发布时间】:2019-03-13 19:50:19
【问题描述】:

你好 :) 只是想在这篇文章的开头说我是一个非常初级的开发人员,并且仍在努力了解使用 os API!

所以我试图创建一个页面,让用户在地图上放置标记,然后使用标记的纬度和经度向谷歌地图 API 发出获取标记的城市名称的请求然后将城市名称放入地图旁边的面板中。但是,我的 GET 请求有问题,它在控制台中返回 400 错误请求错误。

我想显示所有标记被放置的城市的列表,因此我尝试在 URL 中使用插值,以便它可以反复用于放置的图钉返回的所有纬度和经度。所以我使用了以下网址https://maps.googleapis.com/maps/api/geocode/json?latlng=${findCityLng},${findCityLng}&sensor=true&key=MY_API_KEY; (在我的代码中,我输入了我的实际 API 密钥,但已将其取出用于这篇文章)。

我想知道如何修复 URL,以便它仍然可以在任何纬度和经度上使用,而不必对其值进行硬编码,然后它会返回 JSON,我可以深入研究获取城市名称返回 400 错误。我已经用谷歌搜索了,但没有任何关于使用插值创建 url 来发出 API 请求的内容,或者为什么在发出 get 请求时对 google maps api 的 get 请求会返回 400 错误。我已经在谷歌上搜索了几个小时并阅读了 Google Maps API 文档,但无法找到/理解我需要的内容。

任何帮助将不胜感激。

这是我所有的代码(请注意,我必须删除我的 API 密钥,我认为没有它,代码 sn-p 将无法运行,但我不确定如何发布它!抱歉,如果这不正确要做的事情):

console.log('hello world');


let myPlaces = [];
let map;
let findCityLat;
let findCityLng;



  initMap = function() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 36.2048, lng: 138.2529},
      zoom: 6.8
    });



    map.markerList = [];
    map.addListener('click', addPlace);

    const placesFromLocalStorage = JSON.parse(localStorage.getItem('myPlaces'));
    if (Array.isArray(placesFromLocalStorage)) {
      myPlaces = placesFromLocalStorage;
      renderMarkers();                  
    }
                                 



    function addPlace(event) {
    

      myPlaces.push({
        position: event.latLng
      });

      console.log(myPlaces);


      localStorage.setItem('myPlaces', JSON.stringify(myPlaces)); 
      renderMarkers();                                            
    }

    function getCity() {
      for (var i = 0; i < myPlaces.length; i++) {
        findCityLat = myPlaces[i].position.lat;
        findCityLng = myPlaces[i].position.lng;
        console.log(`Lat: ${findCityLat}`);
        console.log(`Lng: ${findCityLng}`);


        const fetchCity = function () {
          const xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function () {
            console.log('readyState', xhr.readyState);
            
            if (xhr.readyState !== 4) {
              return;
            }

            const info = JSON.parse( xhr.response ); 

            const p = document.createElement('p');
            p.innerHTML = `<strong>${ info.result }`; 
            document.body.appendChild( p );
          }
          xhr.open('GET', `https://maps.googleapis.com/maps/api/geocode/json?latlng=${findCityLng},${findCityLng}&sensor=true&key=MY_API_KEY`);
          xhr.send(); // Asynchronous

        };

        window.onload = function() {
          setTimeout(fetchCity,1500)

      }

    }

  }
    getCity();

    function renderMarkers() {
      map.markerList.forEach(m => m.setMap(null)); 
      map.markerList = [];

      myPlaces.forEach((place) => {                     
        const marker = new google.maps.Marker({         
          position: place.position,                     
          map: map
        });

        map.markerList.push(marker);
      });
    }

  }



     initMap();
@import url('https://fonts.googleapis.com/css?family=Quicksand');


* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.main-container {
  margin: 15px;
  display: flex;
}

.sidebar {
  border: rgba(101, 171, 236, 0.56) solid 3px;
  font-size: 0.75em;
  height: 50vh;
  width: 37vw;
  margin: auto;
  text-align: center;
  font-family: 'Quicksand', sans-serif;
  padding: 2px;
}

#map {
  height: 50vh;
  width: 60vw;
  margin: auto;
}

.earthIcon {
  width: 1em;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>My Favourite Places</title>
  <link rel="stylesheet" href="style/master.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
<link rel="shortcut icon" href="images/earth.ico" type="image/x-icon">

</head>
<body>
  <div class="main-container">
    <div class="sidebar">
      <h1>My favourite places in the <img class="earthIcon" src="images/earth.ico"</h1>
      <div id="favPlacesList">

      </div>
    </div>

    <div class="main-content-area">
      <div id="map"></div>
    </div>
  </div>

    <script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>


  <script src="js/main.js"></script>

</body>

</html>

【问题讨论】:

    标签: javascript json google-maps http-status-code-400 get-request


    【解决方案1】:

    您正在向以下网址发出请求:

    `https://maps.googleapis.com/maps/api/geocode/json?latlng=${findCityLng},${findCityLng}&sensor=true&key=MY_API_KEY`
    

    但是,这个url包含两倍的经度,而不是包含纬度和经度。

    它应该更好地与:

    `https://maps.googleapis.com/maps/api/geocode/json?latlng=${findCityLat},${findCityLng}&key=MY_API_KEY`
    

    请注意:

    • 虽然不是导致错误的原因,但我删除了 sensor 参数,因为它不再需要(来源:documentation)
    • 您可以(但不是必须)使用来自Javascript API 的反向地理编码。在后台,它会执行您正在做的事情,调用地理编码 http url,但由于您在 javascript 环境中工作,因此您的代码可能更简单。

    【讨论】:

    • 谢谢!我觉得自己像个白痴!我从 URL 开始很久了,但没有看到!
    【解决方案2】:

    在google maps的请求中,出现这样的错误:

    Google 地图 JavaScript API 错误:InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error

    您可以在此处阅读有关该错误的信息

    https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error

    上面链接的信息提示你需要生成一个新的api密钥here

    然后像这样将新生成的 api 添加到页面中

      <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
      type="text/javascript"></script>
    

    【讨论】:

    • 感谢您的回答 - 只是为了确认一下,我确实有一个 API 密钥并且一直在使用它(我只是从我上面发布的代码中取出它,因为如果您超过一定数量的请求),但你是说除了我原来的 API 密钥之外,我还需要另一个全新的 API 密钥才能工作?
    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多