首页 > 解决方案 > 向 Google Maps API 发出 GET 请求返回错误请求 400 错误 - javascript

问题描述

你好 :) 只是想在这篇文章的开头说我是一个非常初级的开发人员,并且我仍在努力了解使用 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 密钥,我认为没有它代码片段将无法运行,但我不确定如何发布它!抱歉,如果这不是正确的做法):

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>

标签: javascriptjsongoogle-mapshttp-status-code-400get-request

解决方案


在对谷歌地图的请求中,你有这样一个错误:

谷歌地图 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密钥

并像这样将您新生成的api添加到您的页面

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

推荐阅读