-1

I have a working example of how to console log JSON data that i get back from an external API. I also have a working example of how to plot geocode data as a marker on a Google map. I've tried to combine them in the code sample below (its pretty bad).

What I cant do is get both to work together i.e. Call the API and pass the geocode data to be plotted on a map. Here is the example of my code to call an API, load a Google map and console log the geocode data (I've deleted the Google key[so please insert your own to test], but left the RapidAPI key):

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=\, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"  />
  <title>Javascript Calling APIs</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=ENTER_GOOGLE_KEY_HERE&callback=initMap&libraries=&v=weekly" defer></script>
  <style type="text/css">
    /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
    #map {
      height: 100%;
    }

    /* Optional: Makes the sample page fill the window. */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>
  <h1>Test</h1>
  <div id="map"></div>
  <p id="demo"></p>

  <input type="text" placeholder="Type something..." id="myInput">
  <button type="button" onclick="getInputValue();">Get Value</button>


  <script>
  function getInputValue() {
  var myHeaders = new Headers();
  myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");

  var town = document.getElementById("myInput").value;

  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };
}

var myHeaders = new Headers();
myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");
  const api_url = 'https://wyre-data.p.rapidapi.com/restaurants/town'
  var town = document.getElementById("myInput").value;
  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

  async function getTown() {
    const response = await fetch(api_url + '/' + town, requestOptions);
    const data = await response.json();
    console.log(data);
    let la = data[2].Geocode_Latitude;
    let lo = data[2].Geocode_Longitude;
    let pot = {lat: la, lng: lo};
        console.log(pot);
  }

  getTown();

      let map;

      function initMap() {
        map = new google.maps.Map(document.getElementById("map"), {
          center: {
            lat: 53.4808,
            lng: -2.2426
          },
          zoom: 7,
        });

  addMarker(pot);

  //add marker function
  function addMarker(coords){
    var marker = new google.maps.Marker({
    position:coords,
    map:map,
    icon:'pin.png'
    });
  }
  };

How would I plot the results of a town search on a map? Taking the lat/lng from the API return and plotting these as markers. Here is an example of the JSON response:

AddressLine2: "Hallgate Lane"
AddressLine3: "Stalmine"
BusinessName: "MCCOLLS"
Geocode_Latitude: 53.901518
Geocode_Longitude: -2.953877
PostCode: "FY6 0LA"
RatingValue: 5
_id: "5fc96b3a9c728ca91c564485"
  • What `map`? Do you want a `google.maps.Marker`? [Google Example for adding a marker to a map](https://developers.google.com/maps/documentation/javascript/examples/marker-simple), although the related question: [Google Maps JS API v3 - Simple Multiple Marker Example](https://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) might get you further. – geocodezip Dec 11 '20 at 00:43
  • Yes a google map. I can plot markers on a google map. I just cant plot the lat/lngs from the API onto a map. I can console.log the lat/lngs fro the API but I can't pass the lat/lng result from the API to a function that will plot the marker – vern funnell Dec 11 '20 at 01:19
  • 1
    Can you provide a sample of the JSON format returned by the service (can be test data)? And your code to create the map? Preferably in the way you are trying to display the markers (i.e. a [mcve] that demonstrates the issue). The code you currently have in your question displays how to query the API, but doesn't work as the key isn't valid, and doesn't display a map. – geocodezip Dec 11 '20 at 03:14
  • Hi, ive added my code that shows my attempt to combine the API call with the Google map plot. Its pretty bad and I'm struggling with how to overcome local scope of a function with global scope (as im new to this). I'll post test JSON return data as well. – vern funnell Dec 11 '20 at 18:09

1 Answers1

1

To put a marker on your map based on the response from the API, add this code to the processing of the response:

let pot = { // existing code
  lat: la,
  lng: lo
};
let marker = new google.maps.Marker({
  position: pot,
  map: map
}) 

However, you will also need to rearrange your code to make the request when the getInputValue function runs (currently it runs before the map is created, with the initial value of the <input> field (which in the posted code is empty).

Something like this:

function getInputValue() {
  var myHeaders = new Headers();
  myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");

  var town = document.getElementById("myInput").value;

  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };
  var myHeaders = new Headers();
  myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");
  const api_url = 'https://wyre-data.p.rapidapi.com/restaurants/town'
  var town = document.getElementById("myInput").value;
  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

  function getTown() {
    const response = await fetch(api_url + '/' + town, requestOptions);
    const data = await response.json();
    console.log(data);
    let la = data[0].Geocode_Latitude;
    let lo = data[0].Geocode_Longitude;
    let pot = {
      lat: la,
      lng: lo
    };
    let marker = new google.maps.Marker({
      position: pot,
      map: map
    })
    console.log(pot);
  }

  getTown();

}

proof of concept fiddle

enter image description here

code snippet:

function getInputValue() {
  var myHeaders = new Headers();
  myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");

  var town = document.getElementById("myInput").value;

  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };
  var myHeaders = new Headers();
  myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");
  const api_url = 'https://wyre-data.p.rapidapi.com/restaurants/town'
  var town = document.getElementById("myInput").value;
  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

  function getTown() {
    // use provided response instead of response from server
    //  const response = await fetch(api_url + '/' + town, requestOptions);
    //  const data = await response.json();
    const data = [{
      AddressLine2: "Hallgate Lane",
      AddressLine3: "Stalmine",
      BusinessName: "MCCOLLS",
      Geocode_Latitude: 53.901518,
      Geocode_Longitude: -2.953877,
      PostCode: "FY6 0LA",
      RatingValue: 5,
      _id: "5fc96b3a9c728ca91c564485",
    }];
    console.log(data);
    let la = data[0].Geocode_Latitude;
    let lo = data[0].Geocode_Longitude;
    let pot = {
      lat: la,
      lng: lo
    };
    let marker = new google.maps.Marker({
      position: pot,
      map: map
    })
    console.log(pot);
  }

  getTown();

}


let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: {
      lat: 53.4808,
      lng: -2.2426
    },
    zoom: 7,
  });

  addMarker(pot);

  //add marker function
  function addMarker(coords) {
    var marker = new google.maps.Marker({
      position: coords,
      map: map,
      icon: 'pin.png'
    });
  }
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 60%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Markers</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
      <h1>Test</h1>
  <div id="map"></div>
  <p id="demo"></p>

  <input type="text" placeholder="Type something..." id="myInput">
  <button type="button" onclick="getInputValue();">Get Value</button>
  </body>
</html>
geocodezip
  • 158,664
  • 13
  • 220
  • 245