title: Making GET request to Google Maps API returning bad request 400 error - javascript
body: <p>Hello :) Just want to preface this post by saying i am a VERY junior dev and am still trying to get my head around the use os APIs! </p>
  
  <p>So I am attempting to create a page that lets users drop markers on a map and then use the latitude and longitude of the marker to make a get request to the google maps API for the name of the city the marker was dropped on and then to put the name of the city into a panel next to the map. BUT, i am having problems with my GET request and it returning a 400 bad request error in the console. </p>
  
  <p>I want to display a list of all the cities the markers were dropped on and so i am attempting to use interpolation in the URL so that it can be used over and over for all the latitudes and longitudes returned by the dropped pins. So i have used the following url <code>https://maps.googleapis.com/maps/api/geocode/json?latlng=${findCityLng},${findCityLng}&amp;sensor=true&amp;key=MY_API_KEY</code>; (In my code i have entered my actual API key but have taken it out for this post). </p>
  
  <p>I am wanting to know how to fix the URL so that it can still be used on any lat and long without having to hard code their values and so that it will then return JSON i can dig into the get the city name instead of returning the 400 error. I have googled and googled but there is nothing on using interpolation to create the url to make the API requests to or why a get request to the google maps api would return a 400 error when making a get request. I have been googling for hours now and reading the Google Maps API docs but haven't been able to find/understand what i need.</p>
  
  <p>Any help would be greatly appreciated. </p>
  
  <p>Here is all my code (please note i have had to remove my API key and i dont think the code snippet will run without it but i am unsure of how else to post it! sorry if this is not the correct thing to do):</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>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 &lt; 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 = `&lt;strong&gt;${ info.result }`; 
              document.body.appendChild( p );
            }
            xhr.open('GET', `https://maps.googleapis.com/maps/api/geocode/json?latlng=${findCityLng},${findCityLng}&amp;sensor=true&amp;key=MY_API_KEY`);
            xhr.send(); // Asynchronous
  
          };
  
          window.onload = function() {
            setTimeout(fetchCity,1500)
  
        }
  
      }
  
    }
      getCity();
  
      function renderMarkers() {
        map.markerList.forEach(m =&gt; m.setMap(null)); 
        map.markerList = [];
  
        myPlaces.forEach((place) =&gt; {                     
          const marker = new google.maps.Marker({         
            position: place.position,                     
            map: map
          });
  
          map.markerList.push(marker);
        });
      }
  
    }
  
  
  
       initMap();</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>@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;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt;
    &lt;title&gt;My Favourite Places&lt;/title&gt;
    &lt;link rel="stylesheet" href="style/master.css"&gt;
    &lt;link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"&gt;
  &lt;link rel="shortcut icon" href="images/earth.ico" type="image/x-icon"&gt;
  
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div class="main-container"&gt;
      &lt;div class="sidebar"&gt;
        &lt;h1&gt;My favourite places in the &lt;img class="earthIcon" src="images/earth.ico"&lt;/h1&gt;
        &lt;div id="favPlacesList"&gt;
  
        &lt;/div&gt;
      &lt;/div&gt;
  
      &lt;div class="main-content-area"&gt;
        &lt;div id="map"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  
      &lt;script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&amp;libraries=places"&gt;&lt;/script&gt;
  
  
    &lt;script src="js/main.js"&gt;&lt;/script&gt;
  
  &lt;/body&gt;
  
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>