向Google Maps API发出GET请求,返回错误请求400错误-javascript

时间:2018-10-09 05:52:02

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

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

因此,我正在尝试创建一个页面,该页面允许用户在地图上放置标记,然后使用标记的纬度和经度向Google Maps 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错误。我已经用谷歌和谷歌搜索,但没有关于使用插值法创建向API提出请求的URL的信息,或者为什么对Google Maps api的获取请求在做出获取请求时会返回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>

2 个答案:

答案 0 :(得分:1)

在请求Google地图时,您遇到这样的错误:

  

Google Maps 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>

答案 1 :(得分:0)

您正在请求以下网址:

`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环境中工作,因此为您提供的代码可能会更简单。