Elli-Jayne Willard
Elli-Jayne Willard

Reputation: 13

Making GET request to Google Maps API returning bad request 400 error - javascript

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!

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.

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 https://maps.googleapis.com/maps/api/geocode/json?latlng=${findCityLng},${findCityLng}&sensor=true&key=MY_API_KEY; (In my code i have entered my actual API key but have taken it out for this post).

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.

Any help would be greatly appreciated.

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):

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>

Upvotes: 1

Views: 4001

Answers (2)

Michel
Michel

Reputation: 28239

You are making a request to the following url:

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

However, this url contains twice the longitude, instead of containing the latitude and longitude.

It should work better with:

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

Please note:

  • Although not the cause of the error I removed the sensor parameter as it is no longer required (source: documentation)
  • You could (but don't have to) use the Reverse Geocode from the Javascript API. Under the hood it does what you're doing, calling the geocode http url, but since you work in a javascript environment the code for you may be simpler.

Upvotes: 1

Marat Badykov
Marat Badykov

Reputation: 844

In the request for google maps, you have such an error:

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

Here you can read information about that error

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

Information on the link above suggests that you need to generate a new api key here

And add your newly generated api to your page like this

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

Upvotes: 1

Related Questions