How can I output Google Places details into a JSON file?

566 Views Asked by At

I'm trying to loop through Google Place IDs and gather data from each place and then output the place details into one single JSON file which could later be imported into a map. The importing stage is not a concern but I'm struggling to get the data into the JSON file to begin with. What I have currently is below.

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&key=APIKEY"></script>

var placeid_list = [{
  "placeid": 'ChIJryijc9s0K4gRG9aU7SDTXdA',
}, {
  "placeid": 'ChIJaZ6Hg4iAhYARxTsHnDFJ9zE',
}, {
  "placeid": 'ChIJl64IQXrYzUwR8CVOTRf_h3o',
}, {
  "placeid": 'ChIJBTMkuph-zkwR9oEF8Nv3Z0o',
}, {
  "placeid": 'ChIJ4QbSBj8IzkwRGi0ILu03_VA',
}, {
  "placeid": 'ChIJc2nSALkEdkgRkuoJJBfzkUI',
}, {
  "placeid": 'ChIJmzrzi9Y0K4gRgXUc3sTY7RU',
}];

function setPlaces() {

var json = placeid_list;
  
  for (var i = 0, length = json.length; i < length; i++) {
      var data = json[i];
      createPlace(data);
  }
}
function createPlace(data) {
          var service = new google.maps.places.PlacesService();
      service.getDetails({
          placeId: data.placeid
      }, function (result, status) {
          if (status != google.maps.places.PlacesServiceStatus.OK) {

            alert(status);
              return;
          }
          
          placeResults(data, result);
      });
}
function placeResults(data, result) {

        console.log(result.name);
}

Currently I'm just trying to output each of the Place names into a console.log but nothing seems to be showing. It doesn't look like I'm getting any errors in the console either so I'm not too sure where I'm going wrong.

Looking at Google's documentation, I'm not sure if I have to make use of

console.log(JSON.stringify(response.data));

Would this help me to put the details of each of the places into one large JSON file? I'm not too sure how I can implement it with what I currently have. I don't have a great deal of expertise in using javascript but I'm hoping that I'm not too far away from a solution. Thanks

1

There are 1 best solutions below

1
geocodezip On

You a typo in youre code:

var service = new google.maps.places.PlacesService();

Per the documentation:

Constructor
PlacesService(attrContainer)
Parameters:
attrContainer: HTMLDivElement|Map
Creates a new instance of the PlacesService that renders attributions in the specified container.

The PlacesService constructor has a required argument, either a google.maps.Map object or an HTMLDivElement that can be used to render attributions.

So the referenced line should be:

var service = new google.maps.places.PlacesService(map);

Or:

var service = new google.maps.places.PlacesService(document.getElementById("attributionDiv");  
// where attributionDiv is a div that is displayed on your page

Proof of concept fiddle

Outputs:

Alo
Ottawa International Airport
lastminute.com London Eye
Four Seasons Hotel San Francisco
CN Tower
Glenn P Cowan, Chartered Professional Accountant
KB Media Corp

code snippet:

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: {
      lat: -33.866,
      lng: 151.196
    },
    zoom: 15,
  });
  const request = {
    placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4",
    fields: ["name", "formatted_address", "place_id", "geometry"],
  };
  const infowindow = new google.maps.InfoWindow();
  const service = new google.maps.places.PlacesService(map);

  var placeid_list = [{
    "placeid": 'ChIJryijc9s0K4gRG9aU7SDTXdA',
  }, {
    "placeid": 'ChIJaZ6Hg4iAhYARxTsHnDFJ9zE',
  }, {
    "placeid": 'ChIJl64IQXrYzUwR8CVOTRf_h3o',
  }, {
    "placeid": 'ChIJBTMkuph-zkwR9oEF8Nv3Z0o',
  }, {
    "placeid": 'ChIJ4QbSBj8IzkwRGi0ILu03_VA',
  }, {
    "placeid": 'ChIJc2nSALkEdkgRkuoJJBfzkUI',
  }, {
    "placeid": 'ChIJmzrzi9Y0K4gRgXUc3sTY7RU',
  }];

  function setPlaces() {

    var json = placeid_list;

    for (var i = 0, length = json.length; i < length; i++) {
      var data = json[i];
      createPlace(data);
    }
  }

  function createPlace(data) {
    var service = new google.maps.places.PlacesService(map);
    console.log(data);
    service.getDetails({
      placeId: data.placeid,
      fields: ["name", "formatted_address", "place_id", "geometry"],
    }, function(result, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {

        alert(status);
        return;
      }

      placeResults(data, result);
    });
  }

  function placeResults(data, result) {

    console.log(result.name);
    document.getElementById("placeResults").innerHTML += result.name + "<br>";
  }
  setPlaces();
}

window.initMap = initMap;
/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */

#map {
  height: 50%;
}


/* 
 * Optional: Makes the sample page fill the window. 
 */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Place Details</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="placeResults"></div>
  <div id="map"></div>

  <!-- 
     The `defer` attribute causes the callback to execute after the full HTML
     document has been parsed. For non-blocking uses, avoiding race conditions,
     and consistent behavior across browsers, consider loading using Promises
     with https://www.npmjs.com/package/@googlemaps/js-api-loader.
    -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly" defer></script>
</body>

</html>